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

View as plain text