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 may resolve 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. At any point in
    51  // time this state variable determines which data on N may be accessed. As
    52  // state monotonically progresses, any data available at state M may be
    53  // accessed without acquiring the mutex at state N, provided N >= M.
    54  //
    55  // GLOSSARY: Here are a few terms used in this file to describe Named types:
    56  //  - We say that a Named type is "instantiated" if it has been constructed by
    57  //    instantiating a generic named type with type arguments.
    58  //  - We say that a Named type is "declared" if it corresponds to a type
    59  //    declaration in the source. Instantiated named types correspond to a type
    60  //    instantiation in the source, not a declaration. But their Origin type is
    61  //    a declared type.
    62  //  - We say that a Named type is "resolved" if its RHS information has been
    63  //    loaded or fully type-checked. For Named types constructed from export
    64  //    data, this may involve invoking a loader function to extract information
    65  //    from export data. For instantiated named types this involves reading
    66  //    information from their origin.
    67  //  - We say that a Named type is "expanded" if it is an instantiated type and
    68  //    type parameters in its underlying type and methods have been substituted
    69  //    with the type arguments from the instantiation. A type may be partially
    70  //    expanded if some but not all of these details have been substituted.
    71  //    Similarly, we refer to these individual details (underlying type or
    72  //    method) as being "expanded".
    73  //  - When all information is known for a named type, we say it is "complete".
    74  //
    75  // Some invariants to keep in mind: each declared Named type has a single
    76  // corresponding object, and that object's type is the (possibly generic) Named
    77  // type. Declared Named types are identical if and only if their pointers are
    78  // identical. On the other hand, multiple instantiated Named types may be
    79  // identical even though their pointers are not identical. One has to use
    80  // Identical to compare them. For instantiated named types, their obj is a
    81  // synthetic placeholder that records their position of the corresponding
    82  // instantiation in the source (if they were constructed during type checking).
    83  //
    84  // To prevent infinite expansion of named instances that are created outside of
    85  // type-checking, instances share a Context with other instances created during
    86  // their expansion. Via the pidgeonhole principle, this guarantees that in the
    87  // presence of a cycle of named types, expansion will eventually find an
    88  // existing instance in the Context and short-circuit the expansion.
    89  //
    90  // Once an instance is complete, we can nil out this shared Context to unpin
    91  // memory, though this Context may still be held by other incomplete instances
    92  // in its "lineage".
    93  
    94  // A Named represents a named (defined) type.
    95  //
    96  // A declaration such as:
    97  //
    98  //	type S struct { ... }
    99  //
   100  // creates a defined type whose underlying type is a struct,
   101  // and binds this type to the object S, a [TypeName].
   102  // Use [Named.Underlying] to access the underlying type.
   103  // Use [Named.Obj] to obtain the object S.
   104  //
   105  // Before type aliases (Go 1.9), the spec called defined types "named types".
   106  type Named struct {
   107  	check *Checker  // non-nil during type-checking; nil otherwise
   108  	obj   *TypeName // corresponding declared object for declared types; see above for instantiated types
   109  
   110  	// fromRHS holds the type (on RHS of declaration) this *Named type is derived
   111  	// from (for cycle reporting). Only used by validType, and therefore does not
   112  	// require synchronization.
   113  	fromRHS Type
   114  
   115  	// information for instantiated types; nil otherwise
   116  	inst *instance
   117  
   118  	mu         sync.Mutex     // guards all fields below
   119  	state_     uint32         // the current state of this type; must only be accessed atomically
   120  	underlying Type           // possibly a *Named during setup; never a *Named once set up completely
   121  	tparams    *TypeParamList // type parameters, or nil
   122  
   123  	// methods declared for this type (not the method set of this type)
   124  	// Signatures are type-checked lazily.
   125  	// For non-instantiated types, this is a fully populated list of methods. For
   126  	// instantiated types, methods are individually expanded when they are first
   127  	// accessed.
   128  	methods []*Func
   129  
   130  	// loader may be provided to lazily load type parameters, underlying type, methods, and delayed functions
   131  	loader func(*Named) ([]*TypeParam, Type, []*Func, []func())
   132  }
   133  
   134  // instance holds information that is only necessary for instantiated named
   135  // types.
   136  type instance struct {
   137  	orig            *Named    // original, uninstantiated type
   138  	targs           *TypeList // type arguments
   139  	expandedMethods int       // number of expanded methods; expandedMethods <= len(orig.methods)
   140  	ctxt            *Context  // local Context; set to nil after full expansion
   141  }
   142  
   143  // namedState represents the possible states that a named type may assume.
   144  type namedState uint32
   145  
   146  // Note: the order of states is relevant
   147  const (
   148  	unresolved namedState = iota // tparams, underlying type and methods might be unavailable
   149  	resolved                     // resolve has run; methods might be unexpanded (for instances)
   150  	loaded                       // loader has run; constraints might be unexpanded (for generic types)
   151  	complete                     // all data is known
   152  )
   153  
   154  // NewNamed returns a new named type for the given type name, underlying type, and associated methods.
   155  // If the given type name obj doesn't have a type yet, its type is set to the returned named type.
   156  // The underlying type must not be a *Named.
   157  func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
   158  	if asNamed(underlying) != nil {
   159  		panic("underlying type must not be *Named")
   160  	}
   161  	return (*Checker)(nil).newNamed(obj, underlying, methods)
   162  }
   163  
   164  // resolve resolves the type parameters, methods, and underlying type of n.
   165  // This information may be loaded from a provided loader function, or computed
   166  // from an origin type (in the case of instances).
   167  //
   168  // After resolution, the type parameters, methods, and underlying type of n are
   169  // accessible; but if n is an instantiated type, its methods may still be
   170  // unexpanded.
   171  func (n *Named) resolve() *Named {
   172  	if n.state() > unresolved { // avoid locking below
   173  		return n
   174  	}
   175  
   176  	// TODO(rfindley): if n.check is non-nil we can avoid locking here, since
   177  	// type-checking is not concurrent. Evaluate if this is worth doing.
   178  	n.mu.Lock()
   179  	defer n.mu.Unlock()
   180  
   181  	if n.state() > unresolved {
   182  		return n
   183  	}
   184  
   185  	if n.inst != nil {
   186  		assert(n.underlying == nil) // n is an unresolved instance
   187  		assert(n.loader == nil)     // instances are created by instantiation, in which case n.loader is nil
   188  
   189  		orig := n.inst.orig
   190  		orig.resolve()
   191  		underlying := n.expandUnderlying()
   192  
   193  		n.tparams = orig.tparams
   194  		n.underlying = underlying
   195  		n.fromRHS = orig.fromRHS // for cycle detection
   196  
   197  		if len(orig.methods) == 0 {
   198  			n.setState(complete) // nothing further to do
   199  			n.inst.ctxt = nil
   200  		} else {
   201  			n.setState(resolved)
   202  		}
   203  		return n
   204  	}
   205  
   206  	// TODO(mdempsky): Since we're passing n to the loader anyway
   207  	// (necessary because types2 expects the receiver type for methods
   208  	// on defined interface types to be the Named rather than the
   209  	// underlying Interface), maybe it should just handle calling
   210  	// SetTypeParams, SetUnderlying, and AddMethod instead?  Those
   211  	// methods would need to support reentrant calls though. It would
   212  	// also make the API more future-proof towards further extensions.
   213  	if n.loader != nil {
   214  		assert(n.underlying == nil)
   215  		assert(n.TypeArgs().Len() == 0) // instances are created by instantiation, in which case n.loader is nil
   216  
   217  		tparams, underlying, methods, delayed := n.loader(n)
   218  		n.loader = nil
   219  
   220  		n.tparams = bindTParams(tparams)
   221  		n.underlying = underlying
   222  		n.fromRHS = underlying // for cycle detection
   223  		n.methods = methods
   224  
   225  		// advance state to avoid deadlock calling delayed functions
   226  		n.setState(loaded)
   227  
   228  		for _, f := range delayed {
   229  			f()
   230  		}
   231  	}
   232  
   233  	n.setState(complete)
   234  	return n
   235  }
   236  
   237  // state atomically accesses the current state of the receiver.
   238  func (n *Named) state() namedState {
   239  	return namedState(atomic.LoadUint32(&n.state_))
   240  }
   241  
   242  // setState atomically stores the given state for n.
   243  // Must only be called while holding n.mu.
   244  func (n *Named) setState(state namedState) {
   245  	atomic.StoreUint32(&n.state_, uint32(state))
   246  }
   247  
   248  // newNamed is like NewNamed but with a *Checker receiver.
   249  func (check *Checker) newNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
   250  	typ := &Named{check: check, obj: obj, fromRHS: underlying, underlying: underlying, methods: methods}
   251  	if obj.typ == nil {
   252  		obj.typ = typ
   253  	}
   254  	// Ensure that typ is always sanity-checked.
   255  	if check != nil {
   256  		check.needsCleanup(typ)
   257  	}
   258  	return typ
   259  }
   260  
   261  // newNamedInstance creates a new named instance for the given origin and type
   262  // arguments, recording pos as the position of its synthetic object (for error
   263  // reporting).
   264  //
   265  // If set, expanding is the named type instance currently being expanded, that
   266  // led to the creation of this instance.
   267  func (check *Checker) newNamedInstance(pos syntax.Pos, orig *Named, targs []Type, expanding *Named) *Named {
   268  	assert(len(targs) > 0)
   269  
   270  	obj := NewTypeName(pos, orig.obj.pkg, orig.obj.name, nil)
   271  	inst := &instance{orig: orig, targs: newTypeList(targs)}
   272  
   273  	// Only pass the expanding context to the new instance if their packages
   274  	// match. Since type reference cycles are only possible within a single
   275  	// package, this is sufficient for the purposes of short-circuiting cycles.
   276  	// Avoiding passing the context in other cases prevents unnecessary coupling
   277  	// of types across packages.
   278  	if expanding != nil && expanding.Obj().pkg == obj.pkg {
   279  		inst.ctxt = expanding.inst.ctxt
   280  	}
   281  	typ := &Named{check: check, obj: obj, inst: inst}
   282  	obj.typ = typ
   283  	// Ensure that typ is always sanity-checked.
   284  	if check != nil {
   285  		check.needsCleanup(typ)
   286  	}
   287  	return typ
   288  }
   289  
   290  func (t *Named) cleanup() {
   291  	assert(t.inst == nil || t.inst.orig.inst == nil)
   292  	// Ensure that every defined type created in the course of type-checking has
   293  	// either non-*Named underlying type, or is unexpanded.
   294  	//
   295  	// This guarantees that we don't leak any types whose underlying type is
   296  	// *Named, because any unexpanded instances will lazily compute their
   297  	// underlying type by substituting in the underlying type of their origin.
   298  	// The origin must have either been imported or type-checked and expanded
   299  	// here, and in either case its underlying type will be fully expanded.
   300  	switch t.underlying.(type) {
   301  	case nil:
   302  		if t.TypeArgs().Len() == 0 {
   303  			panic("nil underlying")
   304  		}
   305  	case *Named, *Alias:
   306  		t.under() // t.under may add entries to check.cleaners
   307  	}
   308  	t.check = nil
   309  }
   310  
   311  // Obj returns the type name for the declaration defining the named type t. For
   312  // instantiated types, this is same as the type name of the origin type.
   313  func (t *Named) Obj() *TypeName {
   314  	if t.inst == nil {
   315  		return t.obj
   316  	}
   317  	return t.inst.orig.obj
   318  }
   319  
   320  // Origin returns the generic type from which the named type t is
   321  // instantiated. If t is not an instantiated type, the result is t.
   322  func (t *Named) Origin() *Named {
   323  	if t.inst == nil {
   324  		return t
   325  	}
   326  	return t.inst.orig
   327  }
   328  
   329  // TypeParams returns the type parameters of the named type t, or nil.
   330  // The result is non-nil for an (originally) generic type even if it is instantiated.
   331  func (t *Named) TypeParams() *TypeParamList { return t.resolve().tparams }
   332  
   333  // SetTypeParams sets the type parameters of the named type t.
   334  // t must not have type arguments.
   335  func (t *Named) SetTypeParams(tparams []*TypeParam) {
   336  	assert(t.inst == nil)
   337  	t.resolve().tparams = bindTParams(tparams)
   338  }
   339  
   340  // TypeArgs returns the type arguments used to instantiate the named type t.
   341  func (t *Named) TypeArgs() *TypeList {
   342  	if t.inst == nil {
   343  		return nil
   344  	}
   345  	return t.inst.targs
   346  }
   347  
   348  // NumMethods returns the number of explicit methods defined for t.
   349  func (t *Named) NumMethods() int {
   350  	return len(t.Origin().resolve().methods)
   351  }
   352  
   353  // Method returns the i'th method of named type t for 0 <= i < t.NumMethods().
   354  //
   355  // For an ordinary or instantiated type t, the receiver base type of this
   356  // method is the named type t. For an uninstantiated generic type t, each
   357  // method receiver is instantiated with its receiver type parameters.
   358  //
   359  // Methods are numbered deterministically: given the same list of source files
   360  // presented to the type checker, or the same sequence of NewMethod and AddMethod
   361  // calls, the mapping from method index to corresponding method remains the same.
   362  // But the specific ordering is not specified and must not be relied on as it may
   363  // change in the future.
   364  func (t *Named) Method(i int) *Func {
   365  	t.resolve()
   366  
   367  	if t.state() >= complete {
   368  		return t.methods[i]
   369  	}
   370  
   371  	assert(t.inst != nil) // only instances should have incomplete methods
   372  	orig := t.inst.orig
   373  
   374  	t.mu.Lock()
   375  	defer t.mu.Unlock()
   376  
   377  	if len(t.methods) != len(orig.methods) {
   378  		assert(len(t.methods) == 0)
   379  		t.methods = make([]*Func, len(orig.methods))
   380  	}
   381  
   382  	if t.methods[i] == nil {
   383  		assert(t.inst.ctxt != nil) // we should still have a context remaining from the resolution phase
   384  		t.methods[i] = t.expandMethod(i)
   385  		t.inst.expandedMethods++
   386  
   387  		// Check if we've created all methods at this point. If we have, mark the
   388  		// type as fully expanded.
   389  		if t.inst.expandedMethods == len(orig.methods) {
   390  			t.setState(complete)
   391  			t.inst.ctxt = nil // no need for a context anymore
   392  		}
   393  	}
   394  
   395  	return t.methods[i]
   396  }
   397  
   398  // expandMethod substitutes type arguments in the i'th method for an
   399  // instantiated receiver.
   400  func (t *Named) expandMethod(i int) *Func {
   401  	// t.orig.methods is not lazy. origm is the method instantiated with its
   402  	// receiver type parameters (the "origin" method).
   403  	origm := t.inst.orig.Method(i)
   404  	assert(origm != nil)
   405  
   406  	check := t.check
   407  	// Ensure that the original method is type-checked.
   408  	if check != nil {
   409  		check.objDecl(origm, nil)
   410  	}
   411  
   412  	origSig := origm.typ.(*Signature)
   413  	rbase, _ := deref(origSig.Recv().Type())
   414  
   415  	// If rbase is t, then origm is already the instantiated method we're looking
   416  	// for. In this case, we return origm to preserve the invariant that
   417  	// traversing Method->Receiver Type->Method should get back to the same
   418  	// method.
   419  	//
   420  	// This occurs if t is instantiated with the receiver type parameters, as in
   421  	// the use of m in func (r T[_]) m() { r.m() }.
   422  	if rbase == t {
   423  		return origm
   424  	}
   425  
   426  	sig := origSig
   427  	// We can only substitute if we have a correspondence between type arguments
   428  	// and type parameters. This check is necessary in the presence of invalid
   429  	// code.
   430  	if origSig.RecvTypeParams().Len() == t.inst.targs.Len() {
   431  		smap := makeSubstMap(origSig.RecvTypeParams().list(), t.inst.targs.list())
   432  		var ctxt *Context
   433  		if check != nil {
   434  			ctxt = check.context()
   435  		}
   436  		sig = check.subst(origm.pos, origSig, smap, t, ctxt).(*Signature)
   437  	}
   438  
   439  	if sig == origSig {
   440  		// No substitution occurred, but we still need to create a new signature to
   441  		// hold the instantiated receiver.
   442  		copy := *origSig
   443  		sig = &copy
   444  	}
   445  
   446  	var rtyp Type
   447  	if origm.hasPtrRecv() {
   448  		rtyp = NewPointer(t)
   449  	} else {
   450  		rtyp = t
   451  	}
   452  
   453  	sig.recv = cloneVar(origSig.recv, rtyp)
   454  	return cloneFunc(origm, sig)
   455  }
   456  
   457  // SetUnderlying sets the underlying type and marks t as complete.
   458  // t must not have type arguments.
   459  func (t *Named) SetUnderlying(underlying Type) {
   460  	assert(t.inst == nil)
   461  	if underlying == nil {
   462  		panic("underlying type must not be nil")
   463  	}
   464  	if asNamed(underlying) != nil {
   465  		panic("underlying type must not be *Named")
   466  	}
   467  	t.resolve().underlying = underlying
   468  	if t.fromRHS == nil {
   469  		t.fromRHS = underlying // for cycle detection
   470  	}
   471  }
   472  
   473  // AddMethod adds method m unless it is already in the method list.
   474  // The method must be in the same package as t, and t must not have
   475  // type arguments.
   476  func (t *Named) AddMethod(m *Func) {
   477  	assert(samePkg(t.obj.pkg, m.pkg))
   478  	assert(t.inst == nil)
   479  	t.resolve()
   480  	if t.methodIndex(m.name, false) < 0 {
   481  		t.methods = append(t.methods, m)
   482  	}
   483  }
   484  
   485  // methodIndex returns the index of the method with the given name.
   486  // If foldCase is set, capitalization in the name is ignored.
   487  // The result is negative if no such method exists.
   488  func (t *Named) methodIndex(name string, foldCase bool) int {
   489  	if name == "_" {
   490  		return -1
   491  	}
   492  	if foldCase {
   493  		for i, m := range t.methods {
   494  			if strings.EqualFold(m.name, name) {
   495  				return i
   496  			}
   497  		}
   498  	} else {
   499  		for i, m := range t.methods {
   500  			if m.name == name {
   501  				return i
   502  			}
   503  		}
   504  	}
   505  	return -1
   506  }
   507  
   508  // Underlying returns the [underlying type] of the named type t, resolving all
   509  // forwarding declarations. Underlying types are never Named, TypeParam, or
   510  // Alias types.
   511  //
   512  // [underlying type]: https://go.dev/ref/spec#Underlying_types.
   513  func (t *Named) Underlying() Type {
   514  	// TODO(gri) Investigate if Unalias can be moved to where underlying is set.
   515  	return Unalias(t.resolve().underlying)
   516  }
   517  
   518  func (t *Named) String() string { return TypeString(t, nil) }
   519  
   520  // ----------------------------------------------------------------------------
   521  // Implementation
   522  //
   523  // TODO(rfindley): reorganize the loading and expansion methods under this
   524  // heading.
   525  
   526  // under returns the expanded underlying type of n0; possibly by following
   527  // forward chains of named types. If an underlying type is found, resolve
   528  // the chain by setting the underlying type for each defined type in the
   529  // chain before returning it. If no underlying type is found or a cycle
   530  // is detected, the result is Typ[Invalid]. If a cycle is detected and
   531  // n0.check != nil, the cycle is reported.
   532  //
   533  // This is necessary because the underlying type of named may be itself a
   534  // named type that is incomplete:
   535  //
   536  //	type (
   537  //		A B
   538  //		B *C
   539  //		C A
   540  //	)
   541  //
   542  // The type of C is the (named) type of A which is incomplete,
   543  // and which has as its underlying type the named type B.
   544  func (n0 *Named) under() Type {
   545  	u := n0.Underlying()
   546  
   547  	// If the underlying type of a defined type is not a defined
   548  	// (incl. instance) type, then that is the desired underlying
   549  	// type.
   550  	var n1 *Named
   551  	switch u1 := u.(type) {
   552  	case nil:
   553  		// After expansion via Underlying(), we should never encounter a nil
   554  		// underlying.
   555  		panic("nil underlying")
   556  	default:
   557  		// common case
   558  		return u
   559  	case *Named:
   560  		// handled below
   561  		n1 = u1
   562  	}
   563  
   564  	if n0.check == nil {
   565  		panic("Named.check == nil but type is incomplete")
   566  	}
   567  
   568  	// Invariant: after this point n0 as well as any named types in its
   569  	// underlying chain should be set up when this function exits.
   570  	check := n0.check
   571  	n := n0
   572  
   573  	seen := make(map[*Named]int) // types that need their underlying type resolved
   574  	var path []Object            // objects encountered, for cycle reporting
   575  
   576  loop:
   577  	for {
   578  		seen[n] = len(seen)
   579  		path = append(path, n.obj)
   580  		n = n1
   581  		if i, ok := seen[n]; ok {
   582  			// cycle
   583  			check.cycleError(path[i:], firstInSrc(path[i:]))
   584  			u = Typ[Invalid]
   585  			break
   586  		}
   587  		u = n.Underlying()
   588  		switch u1 := u.(type) {
   589  		case nil:
   590  			u = Typ[Invalid]
   591  			break loop
   592  		default:
   593  			break loop
   594  		case *Named:
   595  			// Continue collecting *Named types in the chain.
   596  			n1 = u1
   597  		}
   598  	}
   599  
   600  	for n := range seen {
   601  		// We should never have to update the underlying type of an imported type;
   602  		// those underlying types should have been resolved during the import.
   603  		// Also, doing so would lead to a race condition (was go.dev/issue/31749).
   604  		// Do this check always, not just in debug mode (it's cheap).
   605  		if n.obj.pkg != check.pkg {
   606  			panic("imported type with unresolved underlying type")
   607  		}
   608  		n.underlying = u
   609  	}
   610  
   611  	return u
   612  }
   613  
   614  func (n *Named) lookupMethod(pkg *Package, name string, foldCase bool) (int, *Func) {
   615  	n.resolve()
   616  	if samePkg(n.obj.pkg, pkg) || isExported(name) || foldCase {
   617  		// If n is an instance, we may not have yet instantiated all of its methods.
   618  		// Look up the method index in orig, and only instantiate method at the
   619  		// matching index (if any).
   620  		if i := n.Origin().methodIndex(name, foldCase); i >= 0 {
   621  			// For instances, m.Method(i) will be different from the orig method.
   622  			return i, n.Method(i)
   623  		}
   624  	}
   625  	return -1, nil
   626  }
   627  
   628  // context returns the type-checker context.
   629  func (check *Checker) context() *Context {
   630  	if check.ctxt == nil {
   631  		check.ctxt = NewContext()
   632  	}
   633  	return check.ctxt
   634  }
   635  
   636  // expandUnderlying substitutes type arguments in the underlying type n.orig,
   637  // returning the result. Returns Typ[Invalid] if there was an error.
   638  func (n *Named) expandUnderlying() Type {
   639  	check := n.check
   640  	if check != nil && check.conf.Trace {
   641  		check.trace(n.obj.pos, "-- Named.expandUnderlying %s", n)
   642  		check.indent++
   643  		defer func() {
   644  			check.indent--
   645  			check.trace(n.obj.pos, "=> %s (tparams = %s, under = %s)", n, n.tparams.list(), n.underlying)
   646  		}()
   647  	}
   648  
   649  	assert(n.inst.orig.underlying != nil)
   650  	if n.inst.ctxt == nil {
   651  		n.inst.ctxt = NewContext()
   652  	}
   653  
   654  	orig := n.inst.orig
   655  	targs := n.inst.targs
   656  
   657  	if asNamed(orig.underlying) != nil {
   658  		// We should only get a Named underlying type here during type checking
   659  		// (for example, in recursive type declarations).
   660  		assert(check != nil)
   661  	}
   662  
   663  	if orig.tparams.Len() != targs.Len() {
   664  		// Mismatching arg and tparam length may be checked elsewhere.
   665  		return Typ[Invalid]
   666  	}
   667  
   668  	// Ensure that an instance is recorded before substituting, so that we
   669  	// resolve n for any recursive references.
   670  	h := n.inst.ctxt.instanceHash(orig, targs.list())
   671  	n2 := n.inst.ctxt.update(h, orig, n.TypeArgs().list(), n)
   672  	assert(n == n2)
   673  
   674  	smap := makeSubstMap(orig.tparams.list(), targs.list())
   675  	var ctxt *Context
   676  	if check != nil {
   677  		ctxt = check.context()
   678  	}
   679  	underlying := n.check.subst(n.obj.pos, orig.underlying, smap, n, ctxt)
   680  	// If the underlying type of n is an interface, we need to set the receiver of
   681  	// its methods accurately -- we set the receiver of interface methods on
   682  	// the RHS of a type declaration to the defined type.
   683  	if iface, _ := underlying.(*Interface); iface != nil {
   684  		if methods, copied := replaceRecvType(iface.methods, orig, n); copied {
   685  			// If the underlying type doesn't actually use type parameters, it's
   686  			// possible that it wasn't substituted. In this case we need to create
   687  			// a new *Interface before modifying receivers.
   688  			if iface == orig.underlying {
   689  				old := iface
   690  				iface = check.newInterface()
   691  				iface.embeddeds = old.embeddeds
   692  				assert(old.complete) // otherwise we are copying incomplete data
   693  				iface.complete = old.complete
   694  				iface.implicit = old.implicit // should be false but be conservative
   695  				underlying = iface
   696  			}
   697  			iface.methods = methods
   698  			iface.tset = nil // recompute type set with new methods
   699  
   700  			// If check != nil, check.newInterface will have saved the interface for later completion.
   701  			if check == nil { // golang/go#61561: all newly created interfaces must be fully evaluated
   702  				iface.typeSet()
   703  			}
   704  		}
   705  	}
   706  
   707  	return underlying
   708  }
   709  
   710  // safeUnderlying returns the underlying type of typ without expanding
   711  // instances, to avoid infinite recursion.
   712  //
   713  // TODO(rfindley): eliminate this function or give it a better name.
   714  func safeUnderlying(typ Type) Type {
   715  	if t := asNamed(typ); t != nil {
   716  		return t.underlying
   717  	}
   718  	return typ.Underlying()
   719  }
   720  

View as plain text