]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/named.go
go/types, types2: implement Alias proposal (export API)
[gostls13.git] / src / go / types / named.go
1 // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
2
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.
6
7 package types
8
9 import (
10         "go/token"
11         "sync"
12         "sync/atomic"
13 )
14
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.
19 //
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(),
24 //    and methods.
25 //
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
33 //
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).
43 //
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
48 // soon.
49 //
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.
55 //
56 // GLOSSARY: Here are a few terms used in this file to describe Named types:
57 //  - We say that a Named type is "instantiated" if it has been constructed by
58 //    instantiating a generic named type with type arguments.
59 //  - We say that a Named type is "declared" if it corresponds to a type
60 //    declaration in the source. Instantiated named types correspond to a type
61 //    instantiation in the source, not a declaration. But their Origin type is
62 //    a declared type.
63 //  - We say that a Named type is "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".
75 //
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).
84 //
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.
90 //
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
93 // in its "lineage".
94
95 // A Named represents a named (defined) type.
96 type Named struct {
97         check *Checker  // non-nil during type-checking; nil otherwise
98         obj   *TypeName // corresponding declared object for declared types; see above for instantiated types
99
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.
103         fromRHS Type
104
105         // information for instantiated types; nil otherwise
106         inst *instance
107
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
112
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
117         // accessed.
118         methods []*Func
119
120         // loader may be provided to lazily load type parameters, underlying type, and methods.
121         loader func(*Named) (tparams []*TypeParam, underlying Type, methods []*Func)
122 }
123
124 // instance holds information that is only necessary for instantiated named
125 // types.
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
131 }
132
133 // namedState represents the possible states that a named type may assume.
134 type namedState uint32
135
136 const (
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
140 )
141
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")
148         }
149         return (*Checker)(nil).newNamed(obj, underlying, methods)
150 }
151
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).
155 //
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
158 // unexpanded.
159 func (n *Named) resolve() *Named {
160         if n.state() >= resolved { // avoid locking below
161                 return n
162         }
163
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.
166         n.mu.Lock()
167         defer n.mu.Unlock()
168
169         if n.state() >= resolved {
170                 return n
171         }
172
173         if n.inst != nil {
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
176
177                 orig := n.inst.orig
178                 orig.resolve()
179                 underlying := n.expandUnderlying()
180
181                 n.tparams = orig.tparams
182                 n.underlying = underlying
183                 n.fromRHS = orig.fromRHS // for cycle detection
184
185                 if len(orig.methods) == 0 {
186                         n.setState(complete) // nothing further to do
187                         n.inst.ctxt = nil
188                 } else {
189                         n.setState(resolved)
190                 }
191                 return n
192         }
193
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.
201         if n.loader != nil {
202                 assert(n.underlying == nil)
203                 assert(n.TypeArgs().Len() == 0) // instances are created by instantiation, in which case n.loader is nil
204
205                 tparams, underlying, methods := n.loader(n)
206
207                 n.tparams = bindTParams(tparams)
208                 n.underlying = underlying
209                 n.fromRHS = underlying // for cycle detection
210                 n.methods = methods
211                 n.loader = nil
212         }
213
214         n.setState(complete)
215         return n
216 }
217
218 // state atomically accesses the current state of the receiver.
219 func (n *Named) state() namedState {
220         return namedState(atomic.LoadUint32(&n.state_))
221 }
222
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))
227 }
228
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}
232         if obj.typ == nil {
233                 obj.typ = typ
234         }
235         // Ensure that typ is always sanity-checked.
236         if check != nil {
237                 check.needsCleanup(typ)
238         }
239         return typ
240 }
241
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
244 // reporting).
245 //
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)
250
251         obj := NewTypeName(pos, orig.obj.pkg, orig.obj.name, nil)
252         inst := &instance{orig: orig, targs: newTypeList(targs)}
253
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
261         }
262         typ := &Named{check: check, obj: obj, inst: inst}
263         obj.typ = typ
264         // Ensure that typ is always sanity-checked.
265         if check != nil {
266                 check.needsCleanup(typ)
267         }
268         return typ
269 }
270
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.
275         //
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) {
282         case nil:
283                 if t.TypeArgs().Len() == 0 {
284                         panic("nil underlying")
285                 }
286         case *Named:
287                 t.under() // t.under may add entries to check.cleaners
288         }
289         t.check = nil
290 }
291
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 {
295         if t.inst == nil {
296                 return t.obj
297         }
298         return t.inst.orig.obj
299 }
300
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 {
304         if t.inst == nil {
305                 return t
306         }
307         return t.inst.orig
308 }
309
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 }
313
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)
319 }
320
321 // TypeArgs returns the type arguments used to instantiate the named type t.
322 func (t *Named) TypeArgs() *TypeList {
323         if t.inst == nil {
324                 return nil
325         }
326         return t.inst.targs
327 }
328
329 // NumMethods returns the number of explicit methods defined for t.
330 func (t *Named) NumMethods() int {
331         return len(t.Origin().resolve().methods)
332 }
333
334 // Method returns the i'th method of named type t for 0 <= i < t.NumMethods().
335 //
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 {
340         t.resolve()
341
342         if t.state() >= complete {
343                 return t.methods[i]
344         }
345
346         assert(t.inst != nil) // only instances should have incomplete methods
347         orig := t.inst.orig
348
349         t.mu.Lock()
350         defer t.mu.Unlock()
351
352         if len(t.methods) != len(orig.methods) {
353                 assert(len(t.methods) == 0)
354                 t.methods = make([]*Func, len(orig.methods))
355         }
356
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++
361
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) {
365                         t.setState(complete)
366                         t.inst.ctxt = nil // no need for a context anymore
367                 }
368         }
369
370         return t.methods[i]
371 }
372
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)
379         assert(origm != nil)
380
381         check := t.check
382         // Ensure that the original method is type-checked.
383         if check != nil {
384                 check.objDecl(origm, nil)
385         }
386
387         origSig := origm.typ.(*Signature)
388         rbase, _ := deref(origSig.Recv().Type())
389
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
393         // method.
394         //
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() }.
397         if rbase == t {
398                 return origm
399         }
400
401         sig := origSig
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
404         // code.
405         if origSig.RecvTypeParams().Len() == t.inst.targs.Len() {
406                 smap := makeSubstMap(origSig.RecvTypeParams().list(), t.inst.targs.list())
407                 var ctxt *Context
408                 if check != nil {
409                         ctxt = check.context()
410                 }
411                 sig = check.subst(origm.pos, origSig, smap, t, ctxt).(*Signature)
412         }
413
414         if sig == origSig {
415                 // No substitution occurred, but we still need to create a new signature to
416                 // hold the instantiated receiver.
417                 copy := *origSig
418                 sig = &copy
419         }
420
421         var rtyp Type
422         if origm.hasPtrRecv() {
423                 rtyp = NewPointer(t)
424         } else {
425                 rtyp = t
426         }
427
428         sig.recv = substVar(origSig.recv, rtyp)
429         return substFunc(origm, sig)
430 }
431
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")
438         }
439         if asNamed(underlying) != nil {
440                 panic("underlying type must not be *Named")
441         }
442         t.resolve().underlying = underlying
443         if t.fromRHS == nil {
444                 t.fromRHS = underlying // for cycle detection
445         }
446 }
447
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)
452         t.resolve()
453         if i, _ := lookupMethod(t.methods, m.pkg, m.name, false); i < 0 {
454                 t.methods = append(t.methods, m)
455         }
456 }
457
458 // TODO(gri) Investigate if Unalias can be moved to where underlying is set.
459 func (t *Named) Underlying() Type { return Unalias(t.resolve().underlying) }
460 func (t *Named) String() string   { return TypeString(t, nil) }
461
462 // ----------------------------------------------------------------------------
463 // Implementation
464 //
465 // TODO(rfindley): reorganize the loading and expansion methods under this
466 // heading.
467
468 // under returns the expanded underlying type of n0; possibly by following
469 // forward chains of named types. If an underlying type is found, resolve
470 // the chain by setting the underlying type for each defined type in the
471 // chain before returning it. If no underlying type is found or a cycle
472 // is detected, the result is Typ[Invalid]. If a cycle is detected and
473 // n0.check != nil, the cycle is reported.
474 //
475 // This is necessary because the underlying type of named may be itself a
476 // named type that is incomplete:
477 //
478 //      type (
479 //              A B
480 //              B *C
481 //              C A
482 //      )
483 //
484 // The type of C is the (named) type of A which is incomplete,
485 // and which has as its underlying type the named type B.
486 func (n0 *Named) under() Type {
487         u := n0.Underlying()
488
489         // If the underlying type of a defined type is not a defined
490         // (incl. instance) type, then that is the desired underlying
491         // type.
492         var n1 *Named
493         switch u1 := u.(type) {
494         case nil:
495                 // After expansion via Underlying(), we should never encounter a nil
496                 // underlying.
497                 panic("nil underlying")
498         default:
499                 // common case
500                 return u
501         case *Named:
502                 // handled below
503                 n1 = u1
504         }
505
506         if n0.check == nil {
507                 panic("Named.check == nil but type is incomplete")
508         }
509
510         // Invariant: after this point n0 as well as any named types in its
511         // underlying chain should be set up when this function exits.
512         check := n0.check
513         n := n0
514
515         seen := make(map[*Named]int) // types that need their underlying type resolved
516         var path []Object            // objects encountered, for cycle reporting
517
518 loop:
519         for {
520                 seen[n] = len(seen)
521                 path = append(path, n.obj)
522                 n = n1
523                 if i, ok := seen[n]; ok {
524                         // cycle
525                         check.cycleError(path[i:])
526                         u = Typ[Invalid]
527                         break
528                 }
529                 u = n.Underlying()
530                 switch u1 := u.(type) {
531                 case nil:
532                         u = Typ[Invalid]
533                         break loop
534                 default:
535                         break loop
536                 case *Named:
537                         // Continue collecting *Named types in the chain.
538                         n1 = u1
539                 }
540         }
541
542         for n := range seen {
543                 // We should never have to update the underlying type of an imported type;
544                 // those underlying types should have been resolved during the import.
545                 // Also, doing so would lead to a race condition (was go.dev/issue/31749).
546                 // Do this check always, not just in debug mode (it's cheap).
547                 if n.obj.pkg != check.pkg {
548                         panic("imported type with unresolved underlying type")
549                 }
550                 n.underlying = u
551         }
552
553         return u
554 }
555
556 func (n *Named) lookupMethod(pkg *Package, name string, foldCase bool) (int, *Func) {
557         n.resolve()
558         // If n is an instance, we may not have yet instantiated all of its methods.
559         // Look up the method index in orig, and only instantiate method at the
560         // matching index (if any).
561         i, _ := lookupMethod(n.Origin().methods, pkg, name, foldCase)
562         if i < 0 {
563                 return -1, nil
564         }
565         // For instances, m.Method(i) will be different from the orig method.
566         return i, n.Method(i)
567 }
568
569 // context returns the type-checker context.
570 func (check *Checker) context() *Context {
571         if check.ctxt == nil {
572                 check.ctxt = NewContext()
573         }
574         return check.ctxt
575 }
576
577 // expandUnderlying substitutes type arguments in the underlying type n.orig,
578 // returning the result. Returns Typ[Invalid] if there was an error.
579 func (n *Named) expandUnderlying() Type {
580         check := n.check
581         if check != nil && check.conf._Trace {
582                 check.trace(n.obj.pos, "-- Named.expandUnderlying %s", n)
583                 check.indent++
584                 defer func() {
585                         check.indent--
586                         check.trace(n.obj.pos, "=> %s (tparams = %s, under = %s)", n, n.tparams.list(), n.underlying)
587                 }()
588         }
589
590         assert(n.inst.orig.underlying != nil)
591         if n.inst.ctxt == nil {
592                 n.inst.ctxt = NewContext()
593         }
594
595         orig := n.inst.orig
596         targs := n.inst.targs
597
598         if asNamed(orig.underlying) != nil {
599                 // We should only get a Named underlying type here during type checking
600                 // (for example, in recursive type declarations).
601                 assert(check != nil)
602         }
603
604         if orig.tparams.Len() != targs.Len() {
605                 // Mismatching arg and tparam length may be checked elsewhere.
606                 return Typ[Invalid]
607         }
608
609         // Ensure that an instance is recorded before substituting, so that we
610         // resolve n for any recursive references.
611         h := n.inst.ctxt.instanceHash(orig, targs.list())
612         n2 := n.inst.ctxt.update(h, orig, n.TypeArgs().list(), n)
613         assert(n == n2)
614
615         smap := makeSubstMap(orig.tparams.list(), targs.list())
616         var ctxt *Context
617         if check != nil {
618                 ctxt = check.context()
619         }
620         underlying := n.check.subst(n.obj.pos, orig.underlying, smap, n, ctxt)
621         // If the underlying type of n is an interface, we need to set the receiver of
622         // its methods accurately -- we set the receiver of interface methods on
623         // the RHS of a type declaration to the defined type.
624         if iface, _ := underlying.(*Interface); iface != nil {
625                 if methods, copied := replaceRecvType(iface.methods, orig, n); copied {
626                         // If the underlying type doesn't actually use type parameters, it's
627                         // possible that it wasn't substituted. In this case we need to create
628                         // a new *Interface before modifying receivers.
629                         if iface == orig.underlying {
630                                 old := iface
631                                 iface = check.newInterface()
632                                 iface.embeddeds = old.embeddeds
633                                 assert(old.complete) // otherwise we are copying incomplete data
634                                 iface.complete = old.complete
635                                 iface.implicit = old.implicit // should be false but be conservative
636                                 underlying = iface
637                         }
638                         iface.methods = methods
639                         iface.tset = nil // recompute type set with new methods
640
641                         // If check != nil, check.newInterface will have saved the interface for later completion.
642                         if check == nil { // golang/go#61561: all newly created interfaces must be fully evaluated
643                                 iface.typeSet()
644                         }
645                 }
646         }
647
648         return underlying
649 }
650
651 // safeUnderlying returns the underlying type of typ without expanding
652 // instances, to avoid infinite recursion.
653 //
654 // TODO(rfindley): eliminate this function or give it a better name.
655 func safeUnderlying(typ Type) Type {
656         if t := asNamed(typ); t != nil {
657                 return t.underlying
658         }
659         return typ.Underlying()
660 }