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

View as plain text