1 // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
3 // Copyright 2011 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
15 // Type-checking Named types is subtle, because they may be recursively
16 // defined, and because their full details may be spread across multiple
17 // declarations (via methods). For this reason they are type-checked lazily,
18 // to avoid information being accessed before it is complete.
20 // Conceptually, it is helpful to think of named types as having two distinct
21 // sets of information:
22 // - "LHS" information, defining their identity: Obj() and TypeArgs()
23 // - "RHS" information, defining their details: TypeParams(), Underlying(),
26 // In this taxonomy, LHS information is available immediately, but RHS
27 // information is lazy. Specifically, a named type N may be constructed in any
28 // of the following ways:
29 // 1. type-checked from the source
30 // 2. loaded eagerly from export data
31 // 3. loaded lazily from export data (when using unified IR)
32 // 4. instantiated from a generic type
34 // In cases 1, 3, and 4, it is possible that the underlying type or methods of
35 // N may not be immediately available.
36 // - During type-checking, we allocate N before type-checking its underlying
37 // type or methods, so that we may resolve recursive references.
38 // - When loading from export data, we may load its methods and underlying
39 // type lazily using a provided load function.
40 // - After instantiating, we lazily expand the underlying type and methods
41 // (note that instances may be created while still in the process of
42 // type-checking the original type declaration).
44 // In cases 3 and 4 this lazy construction may also occur concurrently, due to
45 // concurrent use of the type checker API (after type checking or importing has
46 // finished). It is critical that we keep track of state, so that Named types
47 // are constructed exactly once and so that we do not access their details too
50 // We achieve this by tracking state with an atomic state variable, and
51 // guarding potentially concurrent calculations with a mutex. At any point in
52 // time this state variable determines which data on N may be accessed. As
53 // state monotonically progresses, any data available at state M may be
54 // accessed without acquiring the mutex at state N, provided N >= M.
56 // GLOSSARY: Here are a few terms used in this file to describe Named types:
57 // - We say that a Named type is "instantiated" if it has been constructed by
58 // instantiating a generic named type with type arguments.
59 // - We say that a Named type is "declared" if it corresponds to a type
60 // declaration in the source. Instantiated named types correspond to a type
61 // instantiation in the source, not a declaration. But their Origin type is
63 // - We say that a Named type is "resolved" if its RHS information has been
64 // loaded or fully type-checked. For Named types constructed from export
65 // data, this may involve invoking a loader function to extract information
66 // from export data. For instantiated named types this involves reading
67 // information from their origin.
68 // - We say that a Named type is "expanded" if it is an instantiated type and
69 // type parameters in its underlying type and methods have been substituted
70 // with the type arguments from the instantiation. A type may be partially
71 // expanded if some but not all of these details have been substituted.
72 // Similarly, we refer to these individual details (underlying type or
73 // method) as being "expanded".
74 // - When all information is known for a named type, we say it is "complete".
76 // Some invariants to keep in mind: each declared Named type has a single
77 // corresponding object, and that object's type is the (possibly generic) Named
78 // type. Declared Named types are identical if and only if their pointers are
79 // identical. On the other hand, multiple instantiated Named types may be
80 // identical even though their pointers are not identical. One has to use
81 // Identical to compare them. For instantiated named types, their obj is a
82 // synthetic placeholder that records their position of the corresponding
83 // instantiation in the source (if they were constructed during type checking).
85 // To prevent infinite expansion of named instances that are created outside of
86 // type-checking, instances share a Context with other instances created during
87 // their expansion. Via the pidgeonhole principle, this guarantees that in the
88 // presence of a cycle of named types, expansion will eventually find an
89 // existing instance in the Context and short-circuit the expansion.
91 // Once an instance is complete, we can nil out this shared Context to unpin
92 // memory, though this Context may still be held by other incomplete instances
95 // A Named represents a named (defined) type.
97 check *Checker // non-nil during type-checking; nil otherwise
98 obj *TypeName // corresponding declared object for declared types; see above for instantiated types
100 // fromRHS holds the type (on RHS of declaration) this *Named type is derived
101 // from (for cycle reporting). Only used by validType, and therefore does not
102 // require synchronization.
105 // information for instantiated types; nil otherwise
108 mu sync.Mutex // guards all fields below
109 state_ uint32 // the current state of this type; must only be accessed atomically
110 underlying Type // possibly a *Named during setup; never a *Named once set up completely
111 tparams *TypeParamList // type parameters, or nil
113 // methods declared for this type (not the method set of this type)
114 // Signatures are type-checked lazily.
115 // For non-instantiated types, this is a fully populated list of methods. For
116 // instantiated types, methods are individually expanded when they are first
120 // loader may be provided to lazily load type parameters, underlying type, and methods.
121 loader func(*Named) (tparams []*TypeParam, underlying Type, methods []*Func)
124 // instance holds information that is only necessary for instantiated named
126 type instance struct {
127 orig *Named // original, uninstantiated type
128 targs *TypeList // type arguments
129 expandedMethods int // number of expanded methods; expandedMethods <= len(orig.methods)
130 ctxt *Context // local Context; set to nil after full expansion
133 // namedState represents the possible states that a named type may assume.
134 type namedState uint32
137 unresolved namedState = iota // tparams, underlying type and methods might be unavailable
138 resolved // resolve has run; methods might be incomplete (for instances)
139 complete // all data is known
142 // NewNamed returns a new named type for the given type name, underlying type, and associated methods.
143 // If the given type name obj doesn't have a type yet, its type is set to the returned named type.
144 // The underlying type must not be a *Named.
145 func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
146 if asNamed(underlying) != nil {
147 panic("underlying type must not be *Named")
149 return (*Checker)(nil).newNamed(obj, underlying, methods)
152 // resolve resolves the type parameters, methods, and underlying type of n.
153 // This information may be loaded from a provided loader function, or computed
154 // from an origin type (in the case of instances).
156 // After resolution, the type parameters, methods, and underlying type of n are
157 // accessible; but if n is an instantiated type, its methods may still be
159 func (n *Named) resolve() *Named {
160 if n.state() >= resolved { // avoid locking below
164 // TODO(rfindley): if n.check is non-nil we can avoid locking here, since
165 // type-checking is not concurrent. Evaluate if this is worth doing.
169 if n.state() >= resolved {
174 assert(n.underlying == nil) // n is an unresolved instance
175 assert(n.loader == nil) // instances are created by instantiation, in which case n.loader is nil
179 underlying := n.expandUnderlying()
181 n.tparams = orig.tparams
182 n.underlying = underlying
183 n.fromRHS = orig.fromRHS // for cycle detection
185 if len(orig.methods) == 0 {
186 n.setState(complete) // nothing further to do
194 // TODO(mdempsky): Since we're passing n to the loader anyway
195 // (necessary because types2 expects the receiver type for methods
196 // on defined interface types to be the Named rather than the
197 // underlying Interface), maybe it should just handle calling
198 // SetTypeParams, SetUnderlying, and AddMethod instead? Those
199 // methods would need to support reentrant calls though. It would
200 // also make the API more future-proof towards further extensions.
202 assert(n.underlying == nil)
203 assert(n.TypeArgs().Len() == 0) // instances are created by instantiation, in which case n.loader is nil
205 tparams, underlying, methods := n.loader(n)
207 n.tparams = bindTParams(tparams)
208 n.underlying = underlying
209 n.fromRHS = underlying // for cycle detection
218 // state atomically accesses the current state of the receiver.
219 func (n *Named) state() namedState {
220 return namedState(atomic.LoadUint32(&n.state_))
223 // setState atomically stores the given state for n.
224 // Must only be called while holding n.mu.
225 func (n *Named) setState(state namedState) {
226 atomic.StoreUint32(&n.state_, uint32(state))
229 // newNamed is like NewNamed but with a *Checker receiver.
230 func (check *Checker) newNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
231 typ := &Named{check: check, obj: obj, fromRHS: underlying, underlying: underlying, methods: methods}
235 // Ensure that typ is always sanity-checked.
237 check.needsCleanup(typ)
242 // newNamedInstance creates a new named instance for the given origin and type
243 // arguments, recording pos as the position of its synthetic object (for error
246 // If set, expanding is the named type instance currently being expanded, that
247 // led to the creation of this instance.
248 func (check *Checker) newNamedInstance(pos token.Pos, orig *Named, targs []Type, expanding *Named) *Named {
249 assert(len(targs) > 0)
251 obj := NewTypeName(pos, orig.obj.pkg, orig.obj.name, nil)
252 inst := &instance{orig: orig, targs: newTypeList(targs)}
254 // Only pass the expanding context to the new instance if their packages
255 // match. Since type reference cycles are only possible within a single
256 // package, this is sufficient for the purposes of short-circuiting cycles.
257 // Avoiding passing the context in other cases prevents unnecessary coupling
258 // of types across packages.
259 if expanding != nil && expanding.Obj().pkg == obj.pkg {
260 inst.ctxt = expanding.inst.ctxt
262 typ := &Named{check: check, obj: obj, inst: inst}
264 // Ensure that typ is always sanity-checked.
266 check.needsCleanup(typ)
271 func (t *Named) cleanup() {
272 assert(t.inst == nil || t.inst.orig.inst == nil)
273 // Ensure that every defined type created in the course of type-checking has
274 // either non-*Named underlying type, or is unexpanded.
276 // This guarantees that we don't leak any types whose underlying type is
277 // *Named, because any unexpanded instances will lazily compute their
278 // underlying type by substituting in the underlying type of their origin.
279 // The origin must have either been imported or type-checked and expanded
280 // here, and in either case its underlying type will be fully expanded.
281 switch t.underlying.(type) {
283 if t.TypeArgs().Len() == 0 {
284 panic("nil underlying")
287 t.under() // t.under may add entries to check.cleaners
292 // Obj returns the type name for the declaration defining the named type t. For
293 // instantiated types, this is same as the type name of the origin type.
294 func (t *Named) Obj() *TypeName {
298 return t.inst.orig.obj
301 // Origin returns the generic type from which the named type t is
302 // instantiated. If t is not an instantiated type, the result is t.
303 func (t *Named) Origin() *Named {
310 // TypeParams returns the type parameters of the named type t, or nil.
311 // The result is non-nil for an (originally) generic type even if it is instantiated.
312 func (t *Named) TypeParams() *TypeParamList { return t.resolve().tparams }
314 // SetTypeParams sets the type parameters of the named type t.
315 // t must not have type arguments.
316 func (t *Named) SetTypeParams(tparams []*TypeParam) {
317 assert(t.inst == nil)
318 t.resolve().tparams = bindTParams(tparams)
321 // TypeArgs returns the type arguments used to instantiate the named type t.
322 func (t *Named) TypeArgs() *TypeList {
329 // NumMethods returns the number of explicit methods defined for t.
330 func (t *Named) NumMethods() int {
331 return len(t.Origin().resolve().methods)
334 // Method returns the i'th method of named type t for 0 <= i < t.NumMethods().
336 // For an ordinary or instantiated type t, the receiver base type of this
337 // method is the named type t. For an uninstantiated generic type t, each
338 // method receiver is instantiated with its receiver type parameters.
339 func (t *Named) Method(i int) *Func {
342 if t.state() >= complete {
346 assert(t.inst != nil) // only instances should have incomplete methods
352 if len(t.methods) != len(orig.methods) {
353 assert(len(t.methods) == 0)
354 t.methods = make([]*Func, len(orig.methods))
357 if t.methods[i] == nil {
358 assert(t.inst.ctxt != nil) // we should still have a context remaining from the resolution phase
359 t.methods[i] = t.expandMethod(i)
360 t.inst.expandedMethods++
362 // Check if we've created all methods at this point. If we have, mark the
363 // type as fully expanded.
364 if t.inst.expandedMethods == len(orig.methods) {
366 t.inst.ctxt = nil // no need for a context anymore
373 // expandMethod substitutes type arguments in the i'th method for an
374 // instantiated receiver.
375 func (t *Named) expandMethod(i int) *Func {
376 // t.orig.methods is not lazy. origm is the method instantiated with its
377 // receiver type parameters (the "origin" method).
378 origm := t.inst.orig.Method(i)
382 // Ensure that the original method is type-checked.
384 check.objDecl(origm, nil)
387 origSig := origm.typ.(*Signature)
388 rbase, _ := deref(origSig.Recv().Type())
390 // If rbase is t, then origm is already the instantiated method we're looking
391 // for. In this case, we return origm to preserve the invariant that
392 // traversing Method->Receiver Type->Method should get back to the same
395 // This occurs if t is instantiated with the receiver type parameters, as in
396 // the use of m in func (r T[_]) m() { r.m() }.
402 // We can only substitute if we have a correspondence between type arguments
403 // and type parameters. This check is necessary in the presence of invalid
405 if origSig.RecvTypeParams().Len() == t.inst.targs.Len() {
406 smap := makeSubstMap(origSig.RecvTypeParams().list(), t.inst.targs.list())
409 ctxt = check.context()
411 sig = check.subst(origm.pos, origSig, smap, t, ctxt).(*Signature)
415 // No substitution occurred, but we still need to create a new signature to
416 // hold the instantiated receiver.
422 if origm.hasPtrRecv() {
428 sig.recv = substVar(origSig.recv, rtyp)
429 return substFunc(origm, sig)
432 // SetUnderlying sets the underlying type and marks t as complete.
433 // t must not have type arguments.
434 func (t *Named) SetUnderlying(underlying Type) {
435 assert(t.inst == nil)
436 if underlying == nil {
437 panic("underlying type must not be nil")
439 if asNamed(underlying) != nil {
440 panic("underlying type must not be *Named")
442 t.resolve().underlying = underlying
443 if t.fromRHS == nil {
444 t.fromRHS = underlying // for cycle detection
448 // AddMethod adds method m unless it is already in the method list.
449 // t must not have type arguments.
450 func (t *Named) AddMethod(m *Func) {
451 assert(t.inst == nil)
453 if i, _ := lookupMethod(t.methods, m.pkg, m.name, false); i < 0 {
454 t.methods = append(t.methods, m)
458 func (t *Named) Underlying() Type { return t.resolve().underlying }
459 func (t *Named) String() string { return TypeString(t, nil) }
461 // ----------------------------------------------------------------------------
464 // TODO(rfindley): reorganize the loading and expansion methods under this
467 // under returns the expanded underlying type of n0; possibly by following
468 // forward chains of named types. If an underlying type is found, resolve
469 // the chain by setting the underlying type for each defined type in the
470 // chain before returning it. If no underlying type is found or a cycle
471 // is detected, the result is Typ[Invalid]. If a cycle is detected and
472 // n0.check != nil, the cycle is reported.
474 // This is necessary because the underlying type of named may be itself a
475 // named type that is incomplete:
483 // The type of C is the (named) type of A which is incomplete,
484 // and which has as its underlying type the named type B.
485 func (n0 *Named) under() Type {
488 // If the underlying type of a defined type is not a defined
489 // (incl. instance) type, then that is the desired underlying
492 switch u1 := u.(type) {
494 // After expansion via Underlying(), we should never encounter a nil
496 panic("nil underlying")
506 panic("Named.check == nil but type is incomplete")
509 // Invariant: after this point n0 as well as any named types in its
510 // underlying chain should be set up when this function exits.
514 seen := make(map[*Named]int) // types that need their underlying type resolved
515 var path []Object // objects encountered, for cycle reporting
520 path = append(path, n.obj)
522 if i, ok := seen[n]; ok {
524 check.cycleError(path[i:])
529 switch u1 := u.(type) {
536 // Continue collecting *Named types in the chain.
541 for n := range seen {
542 // We should never have to update the underlying type of an imported type;
543 // those underlying types should have been resolved during the import.
544 // Also, doing so would lead to a race condition (was go.dev/issue/31749).
545 // Do this check always, not just in debug mode (it's cheap).
546 if n.obj.pkg != check.pkg {
547 panic("imported type with unresolved underlying type")
555 func (n *Named) lookupMethod(pkg *Package, name string, foldCase bool) (int, *Func) {
557 // If n is an instance, we may not have yet instantiated all of its methods.
558 // Look up the method index in orig, and only instantiate method at the
559 // matching index (if any).
560 i, _ := lookupMethod(n.Origin().methods, pkg, name, foldCase)
564 // For instances, m.Method(i) will be different from the orig method.
565 return i, n.Method(i)
568 // context returns the type-checker context.
569 func (check *Checker) context() *Context {
570 if check.ctxt == nil {
571 check.ctxt = NewContext()
576 // expandUnderlying substitutes type arguments in the underlying type n.orig,
577 // returning the result. Returns Typ[Invalid] if there was an error.
578 func (n *Named) expandUnderlying() Type {
580 if check != nil && check.conf._Trace {
581 check.trace(n.obj.pos, "-- Named.expandUnderlying %s", n)
585 check.trace(n.obj.pos, "=> %s (tparams = %s, under = %s)", n, n.tparams.list(), n.underlying)
589 assert(n.inst.orig.underlying != nil)
590 if n.inst.ctxt == nil {
591 n.inst.ctxt = NewContext()
595 targs := n.inst.targs
597 if asNamed(orig.underlying) != nil {
598 // We should only get a Named underlying type here during type checking
599 // (for example, in recursive type declarations).
603 if orig.tparams.Len() != targs.Len() {
604 // Mismatching arg and tparam length may be checked elsewhere.
608 // Ensure that an instance is recorded before substituting, so that we
609 // resolve n for any recursive references.
610 h := n.inst.ctxt.instanceHash(orig, targs.list())
611 n2 := n.inst.ctxt.update(h, orig, n.TypeArgs().list(), n)
614 smap := makeSubstMap(orig.tparams.list(), targs.list())
617 ctxt = check.context()
619 underlying := n.check.subst(n.obj.pos, orig.underlying, smap, n, ctxt)
620 // If the underlying type of n is an interface, we need to set the receiver of
621 // its methods accurately -- we set the receiver of interface methods on
622 // the RHS of a type declaration to the defined type.
623 if iface, _ := underlying.(*Interface); iface != nil {
624 if methods, copied := replaceRecvType(iface.methods, orig, n); copied {
625 // If the underlying type doesn't actually use type parameters, it's
626 // possible that it wasn't substituted. In this case we need to create
627 // a new *Interface before modifying receivers.
628 if iface == orig.underlying {
630 iface = check.newInterface()
631 iface.embeddeds = old.embeddeds
632 assert(old.complete) // otherwise we are copying incomplete data
633 iface.complete = old.complete
634 iface.implicit = old.implicit // should be false but be conservative
637 iface.methods = methods
638 iface.tset = nil // recompute type set with new methods
640 // If check != nil, check.newInterface will have saved the interface for later completion.
641 if check == nil { // golang/go#61561: all newly created interfaces must be fully evaluated
650 // safeUnderlying returns the underlying type of typ without expanding
651 // instances, to avoid infinite recursion.
653 // TODO(rfindley): eliminate this function or give it a better name.
654 func safeUnderlying(typ Type) Type {
655 if t := asNamed(typ); t != nil {
658 return typ.Underlying()