]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/type.go
[dev.typeparams] merge master (2f0da6d) into dev.typeparams
[gostls13.git] / src / go / types / type.go
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package types
6
7 import (
8         "fmt"
9         "go/token"
10 )
11
12 // A Type represents a type of Go.
13 // All types implement the Type interface.
14 type Type interface {
15         // Underlying returns the underlying type of a type
16         // w/o following forwarding chains. Only used by
17         // client packages (here for backward-compatibility).
18         Underlying() Type
19
20         // String returns a string representation of a type.
21         String() string
22 }
23
24 // BasicKind describes the kind of basic type.
25 type BasicKind int
26
27 const (
28         Invalid BasicKind = iota // type is invalid
29
30         // predeclared types
31         Bool
32         Int
33         Int8
34         Int16
35         Int32
36         Int64
37         Uint
38         Uint8
39         Uint16
40         Uint32
41         Uint64
42         Uintptr
43         Float32
44         Float64
45         Complex64
46         Complex128
47         String
48         UnsafePointer
49
50         // types for untyped values
51         UntypedBool
52         UntypedInt
53         UntypedRune
54         UntypedFloat
55         UntypedComplex
56         UntypedString
57         UntypedNil
58
59         // aliases
60         Byte = Uint8
61         Rune = Int32
62 )
63
64 // BasicInfo is a set of flags describing properties of a basic type.
65 type BasicInfo int
66
67 // Properties of basic types.
68 const (
69         IsBoolean BasicInfo = 1 << iota
70         IsInteger
71         IsUnsigned
72         IsFloat
73         IsComplex
74         IsString
75         IsUntyped
76
77         IsOrdered   = IsInteger | IsFloat | IsString
78         IsNumeric   = IsInteger | IsFloat | IsComplex
79         IsConstType = IsBoolean | IsNumeric | IsString
80 )
81
82 // A Basic represents a basic type.
83 type Basic struct {
84         kind BasicKind
85         info BasicInfo
86         name string
87 }
88
89 // Kind returns the kind of basic type b.
90 func (b *Basic) Kind() BasicKind { return b.kind }
91
92 // Info returns information about properties of basic type b.
93 func (b *Basic) Info() BasicInfo { return b.info }
94
95 // Name returns the name of basic type b.
96 func (b *Basic) Name() string { return b.name }
97
98 // An Array represents an array type.
99 type Array struct {
100         len  int64
101         elem Type
102 }
103
104 // NewArray returns a new array type for the given element type and length.
105 // A negative length indicates an unknown length.
106 func NewArray(elem Type, len int64) *Array { return &Array{len: len, elem: elem} }
107
108 // Len returns the length of array a.
109 // A negative result indicates an unknown length.
110 func (a *Array) Len() int64 { return a.len }
111
112 // Elem returns element type of array a.
113 func (a *Array) Elem() Type { return a.elem }
114
115 // A Slice represents a slice type.
116 type Slice struct {
117         elem Type
118 }
119
120 // NewSlice returns a new slice type for the given element type.
121 func NewSlice(elem Type) *Slice { return &Slice{elem: elem} }
122
123 // Elem returns the element type of slice s.
124 func (s *Slice) Elem() Type { return s.elem }
125
126 // A Struct represents a struct type.
127 type Struct struct {
128         fields []*Var
129         tags   []string // field tags; nil if there are no tags
130 }
131
132 // NewStruct returns a new struct with the given fields and corresponding field tags.
133 // If a field with index i has a tag, tags[i] must be that tag, but len(tags) may be
134 // only as long as required to hold the tag with the largest index i. Consequently,
135 // if no field has a tag, tags may be nil.
136 func NewStruct(fields []*Var, tags []string) *Struct {
137         var fset objset
138         for _, f := range fields {
139                 if f.name != "_" && fset.insert(f) != nil {
140                         panic("multiple fields with the same name")
141                 }
142         }
143         if len(tags) > len(fields) {
144                 panic("more tags than fields")
145         }
146         return &Struct{fields: fields, tags: tags}
147 }
148
149 // NumFields returns the number of fields in the struct (including blank and embedded fields).
150 func (s *Struct) NumFields() int { return len(s.fields) }
151
152 // Field returns the i'th field for 0 <= i < NumFields().
153 func (s *Struct) Field(i int) *Var { return s.fields[i] }
154
155 // Tag returns the i'th field tag for 0 <= i < NumFields().
156 func (s *Struct) Tag(i int) string {
157         if i < len(s.tags) {
158                 return s.tags[i]
159         }
160         return ""
161 }
162
163 // A Pointer represents a pointer type.
164 type Pointer struct {
165         base Type // element type
166 }
167
168 // NewPointer returns a new pointer type for the given element (base) type.
169 func NewPointer(elem Type) *Pointer { return &Pointer{base: elem} }
170
171 // Elem returns the element type for the given pointer p.
172 func (p *Pointer) Elem() Type { return p.base }
173
174 // A Tuple represents an ordered list of variables; a nil *Tuple is a valid (empty) tuple.
175 // Tuples are used as components of signatures and to represent the type of multiple
176 // assignments; they are not first class types of Go.
177 type Tuple struct {
178         vars []*Var
179 }
180
181 // NewTuple returns a new tuple for the given variables.
182 func NewTuple(x ...*Var) *Tuple {
183         if len(x) > 0 {
184                 return &Tuple{vars: x}
185         }
186         // TODO(gri) Don't represent empty tuples with a (*Tuple)(nil) pointer;
187         //           it's too subtle and causes problems.
188         return nil
189 }
190
191 // Len returns the number variables of tuple t.
192 func (t *Tuple) Len() int {
193         if t != nil {
194                 return len(t.vars)
195         }
196         return 0
197 }
198
199 // At returns the i'th variable of tuple t.
200 func (t *Tuple) At(i int) *Var { return t.vars[i] }
201
202 // A Signature represents a (non-builtin) function or method type.
203 // The receiver is ignored when comparing signatures for identity.
204 type Signature struct {
205         // We need to keep the scope in Signature (rather than passing it around
206         // and store it in the Func Object) because when type-checking a function
207         // literal we call the general type checker which returns a general Type.
208         // We then unpack the *Signature and use the scope for the literal body.
209         rparams  []*TypeName // receiver type parameters from left to right, or nil
210         tparams  []*TypeName // type parameters from left to right, or nil
211         scope    *Scope      // function scope, present for package-local signatures
212         recv     *Var        // nil if not a method
213         params   *Tuple      // (incoming) parameters from left to right; or nil
214         results  *Tuple      // (outgoing) results from left to right; or nil
215         variadic bool        // true if the last parameter's type is of the form ...T (or string, for append built-in only)
216 }
217
218 // NewSignature returns a new function type for the given receiver, parameters,
219 // and results, either of which may be nil. If variadic is set, the function
220 // is variadic, it must have at least one parameter, and the last parameter
221 // must be of unnamed slice type.
222 func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature {
223         if variadic {
224                 n := params.Len()
225                 if n == 0 {
226                         panic("types.NewSignature: variadic function must have at least one parameter")
227                 }
228                 if _, ok := params.At(n - 1).typ.(*Slice); !ok {
229                         panic("types.NewSignature: variadic parameter must be of unnamed slice type")
230                 }
231         }
232         return &Signature{recv: recv, params: params, results: results, variadic: variadic}
233 }
234
235 // Recv returns the receiver of signature s (if a method), or nil if a
236 // function. It is ignored when comparing signatures for identity.
237 //
238 // For an abstract method, Recv returns the enclosing interface either
239 // as a *Named or an *Interface. Due to embedding, an interface may
240 // contain methods whose receiver type is a different interface.
241 func (s *Signature) Recv() *Var { return s.recv }
242
243 // TParams returns the type parameters of signature s, or nil.
244 func (s *Signature) TParams() []*TypeName { return s.tparams }
245
246 // SetTParams sets the type parameters of signature s.
247 func (s *Signature) SetTParams(tparams []*TypeName) { s.tparams = tparams }
248
249 // Params returns the parameters of signature s, or nil.
250 func (s *Signature) Params() *Tuple { return s.params }
251
252 // Results returns the results of signature s, or nil.
253 func (s *Signature) Results() *Tuple { return s.results }
254
255 // Variadic reports whether the signature s is variadic.
256 func (s *Signature) Variadic() bool { return s.variadic }
257
258 // A Sum represents a set of possible types.
259 // Sums are currently used to represent type lists of interfaces
260 // and thus the underlying types of type parameters; they are not
261 // first class types of Go.
262 type Sum struct {
263         types []Type // types are unique
264 }
265
266 // NewSum returns a new Sum type consisting of the provided
267 // types if there are more than one. If there is exactly one
268 // type, it returns that type. If the list of types is empty
269 // the result is nil.
270 func NewSum(types []Type) Type {
271         if len(types) == 0 {
272                 return nil
273         }
274
275         // What should happen if types contains a sum type?
276         // Do we flatten the types list? For now we check
277         // and panic. This should not be possible for the
278         // current use case of type lists.
279         // TODO(gri) Come up with the rules for sum types.
280         for _, t := range types {
281                 if _, ok := t.(*Sum); ok {
282                         panic("sum type contains sum type - unimplemented")
283                 }
284         }
285
286         if len(types) == 1 {
287                 return types[0]
288         }
289         return &Sum{types: types}
290 }
291
292 // is reports whether all types in t satisfy pred.
293 func (s *Sum) is(pred func(Type) bool) bool {
294         if s == nil {
295                 return false
296         }
297         for _, t := range s.types {
298                 if !pred(t) {
299                         return false
300                 }
301         }
302         return true
303 }
304
305 // An Interface represents an interface type.
306 type Interface struct {
307         methods   []*Func // ordered list of explicitly declared methods
308         types     Type    // (possibly a Sum) type declared with a type list (TODO(gri) need better field name)
309         embeddeds []Type  // ordered list of explicitly embedded types
310
311         allMethods []*Func // ordered list of methods declared with or embedded in this interface (TODO(gri): replace with mset)
312         allTypes   Type    // intersection of all embedded and locally declared types  (TODO(gri) need better field name)
313
314         obj Object // type declaration defining this interface; or nil (for better error messages)
315 }
316
317 // unpack unpacks a type into a list of types.
318 // TODO(gri) Try to eliminate the need for this function.
319 func unpackType(typ Type) []Type {
320         if typ == nil {
321                 return nil
322         }
323         if sum := asSum(typ); sum != nil {
324                 return sum.types
325         }
326         return []Type{typ}
327 }
328
329 // is reports whether interface t represents types that all satisfy pred.
330 func (t *Interface) is(pred func(Type) bool) bool {
331         if t.allTypes == nil {
332                 return false // we must have at least one type! (was bug)
333         }
334         for _, t := range unpackType(t.allTypes) {
335                 if !pred(t) {
336                         return false
337                 }
338         }
339         return true
340 }
341
342 // emptyInterface represents the empty (completed) interface
343 var emptyInterface = Interface{allMethods: markComplete}
344
345 // markComplete is used to mark an empty interface as completely
346 // set up by setting the allMethods field to a non-nil empty slice.
347 var markComplete = make([]*Func, 0)
348
349 // NewInterface returns a new (incomplete) interface for the given methods and embedded types.
350 // Each embedded type must have an underlying type of interface type.
351 // NewInterface takes ownership of the provided methods and may modify their types by setting
352 // missing receivers. To compute the method set of the interface, Complete must be called.
353 //
354 // Deprecated: Use NewInterfaceType instead which allows any (even non-defined) interface types
355 // to be embedded. This is necessary for interfaces that embed alias type names referring to
356 // non-defined (literal) interface types.
357 func NewInterface(methods []*Func, embeddeds []*Named) *Interface {
358         tnames := make([]Type, len(embeddeds))
359         for i, t := range embeddeds {
360                 tnames[i] = t
361         }
362         return NewInterfaceType(methods, tnames)
363 }
364
365 // NewInterfaceType returns a new (incomplete) interface for the given methods and embedded types.
366 // Each embedded type must have an underlying type of interface type (this property is not
367 // verified for defined types, which may be in the process of being set up and which don't
368 // have a valid underlying type yet).
369 // NewInterfaceType takes ownership of the provided methods and may modify their types by setting
370 // missing receivers. To compute the method set of the interface, Complete must be called.
371 func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface {
372         if len(methods) == 0 && len(embeddeds) == 0 {
373                 return &emptyInterface
374         }
375
376         // set method receivers if necessary
377         typ := new(Interface)
378         for _, m := range methods {
379                 if sig := m.typ.(*Signature); sig.recv == nil {
380                         sig.recv = NewVar(m.pos, m.pkg, "", typ)
381                 }
382         }
383
384         // All embedded types should be interfaces; however, defined types
385         // may not yet be fully resolved. Only verify that non-defined types
386         // are interfaces. This matches the behavior of the code before the
387         // fix for #25301 (issue #25596).
388         for _, t := range embeddeds {
389                 if _, ok := t.(*Named); !ok && !IsInterface(t) {
390                         panic("embedded type is not an interface")
391                 }
392         }
393
394         // sort for API stability
395         sortMethods(methods)
396         sortTypes(embeddeds)
397
398         typ.methods = methods
399         typ.embeddeds = embeddeds
400         return typ
401 }
402
403 // NumExplicitMethods returns the number of explicitly declared methods of interface t.
404 func (t *Interface) NumExplicitMethods() int { return len(t.methods) }
405
406 // ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods().
407 // The methods are ordered by their unique Id.
408 func (t *Interface) ExplicitMethod(i int) *Func { return t.methods[i] }
409
410 // NumEmbeddeds returns the number of embedded types in interface t.
411 func (t *Interface) NumEmbeddeds() int { return len(t.embeddeds) }
412
413 // Embedded returns the i'th embedded defined (*Named) type of interface t for 0 <= i < t.NumEmbeddeds().
414 // The result is nil if the i'th embedded type is not a defined type.
415 //
416 // Deprecated: Use EmbeddedType which is not restricted to defined (*Named) types.
417 func (t *Interface) Embedded(i int) *Named { tname, _ := t.embeddeds[i].(*Named); return tname }
418
419 // EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().
420 func (t *Interface) EmbeddedType(i int) Type { return t.embeddeds[i] }
421
422 // NumMethods returns the total number of methods of interface t.
423 // The interface must have been completed.
424 func (t *Interface) NumMethods() int { t.assertCompleteness(); return len(t.allMethods) }
425
426 func (t *Interface) assertCompleteness() {
427         if t.allMethods == nil {
428                 panic("interface is incomplete")
429         }
430 }
431
432 // Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
433 // The methods are ordered by their unique Id.
434 // The interface must have been completed.
435 func (t *Interface) Method(i int) *Func { t.assertCompleteness(); return t.allMethods[i] }
436
437 // Empty reports whether t is the empty interface.
438 func (t *Interface) Empty() bool {
439         if t.allMethods != nil {
440                 // interface is complete - quick test
441                 // A non-nil allTypes may still be empty and represents the bottom type.
442                 return len(t.allMethods) == 0 && t.allTypes == nil
443         }
444         return !t.iterate(func(t *Interface) bool {
445                 return len(t.methods) > 0 || t.types != nil
446         }, nil)
447 }
448
449 // HasTypeList reports whether interface t has a type list, possibly from an embedded type.
450 func (t *Interface) HasTypeList() bool {
451         if t.allMethods != nil {
452                 // interface is complete - quick test
453                 return t.allTypes != nil
454         }
455
456         return t.iterate(func(t *Interface) bool {
457                 return t.types != nil
458         }, nil)
459 }
460
461 // IsComparable reports whether interface t is or embeds the predeclared interface "comparable".
462 func (t *Interface) IsComparable() bool {
463         if t.allMethods != nil {
464                 // interface is complete - quick test
465                 _, m := lookupMethod(t.allMethods, nil, "==")
466                 return m != nil
467         }
468
469         return t.iterate(func(t *Interface) bool {
470                 _, m := lookupMethod(t.methods, nil, "==")
471                 return m != nil
472         }, nil)
473 }
474
475 // IsConstraint reports t.HasTypeList() || t.IsComparable().
476 func (t *Interface) IsConstraint() bool {
477         if t.allMethods != nil {
478                 // interface is complete - quick test
479                 if t.allTypes != nil {
480                         return true
481                 }
482                 _, m := lookupMethod(t.allMethods, nil, "==")
483                 return m != nil
484         }
485
486         return t.iterate(func(t *Interface) bool {
487                 if t.types != nil {
488                         return true
489                 }
490                 _, m := lookupMethod(t.methods, nil, "==")
491                 return m != nil
492         }, nil)
493 }
494
495 // iterate calls f with t and then with any embedded interface of t, recursively, until f returns true.
496 // iterate reports whether any call to f returned true.
497 func (t *Interface) iterate(f func(*Interface) bool, seen map[*Interface]bool) bool {
498         if f(t) {
499                 return true
500         }
501         for _, e := range t.embeddeds {
502                 // e should be an interface but be careful (it may be invalid)
503                 if e := asInterface(e); e != nil {
504                         // Cyclic interfaces such as "type E interface { E }" are not permitted
505                         // but they are still constructed and we need to detect such cycles.
506                         if seen[e] {
507                                 continue
508                         }
509                         if seen == nil {
510                                 seen = make(map[*Interface]bool)
511                         }
512                         seen[e] = true
513                         if e.iterate(f, seen) {
514                                 return true
515                         }
516                 }
517         }
518         return false
519 }
520
521 // isSatisfiedBy reports whether interface t's type list is satisfied by the type typ.
522 // If the the type list is empty (absent), typ trivially satisfies the interface.
523 // TODO(gri) This is not a great name. Eventually, we should have a more comprehensive
524 //           "implements" predicate.
525 func (t *Interface) isSatisfiedBy(typ Type) bool {
526         t.Complete()
527         if t.allTypes == nil {
528                 return true
529         }
530         types := unpackType(t.allTypes)
531         return includes(types, typ) || includes(types, under(typ))
532 }
533
534 // Complete computes the interface's method set. It must be called by users of
535 // NewInterfaceType and NewInterface after the interface's embedded types are
536 // fully defined and before using the interface type in any way other than to
537 // form other types. The interface must not contain duplicate methods or a
538 // panic occurs. Complete returns the receiver.
539 func (t *Interface) Complete() *Interface {
540         // TODO(gri) consolidate this method with Checker.completeInterface
541         if t.allMethods != nil {
542                 return t
543         }
544
545         t.allMethods = markComplete // avoid infinite recursion
546
547         var todo []*Func
548         var methods []*Func
549         var seen objset
550         addMethod := func(m *Func, explicit bool) {
551                 switch other := seen.insert(m); {
552                 case other == nil:
553                         methods = append(methods, m)
554                 case explicit:
555                         panic("duplicate method " + m.name)
556                 default:
557                         // check method signatures after all locally embedded interfaces are computed
558                         todo = append(todo, m, other.(*Func))
559                 }
560         }
561
562         for _, m := range t.methods {
563                 addMethod(m, true)
564         }
565
566         allTypes := t.types
567
568         for _, typ := range t.embeddeds {
569                 utyp := under(typ)
570                 etyp := asInterface(utyp)
571                 if etyp == nil {
572                         if utyp != Typ[Invalid] {
573                                 panic(fmt.Sprintf("%s is not an interface", typ))
574                         }
575                         continue
576                 }
577                 etyp.Complete()
578                 for _, m := range etyp.allMethods {
579                         addMethod(m, false)
580                 }
581                 allTypes = intersect(allTypes, etyp.allTypes)
582         }
583
584         for i := 0; i < len(todo); i += 2 {
585                 m := todo[i]
586                 other := todo[i+1]
587                 if !Identical(m.typ, other.typ) {
588                         panic("duplicate method " + m.name)
589                 }
590         }
591
592         if methods != nil {
593                 sortMethods(methods)
594                 t.allMethods = methods
595         }
596         t.allTypes = allTypes
597
598         return t
599 }
600
601 // A Map represents a map type.
602 type Map struct {
603         key, elem Type
604 }
605
606 // NewMap returns a new map for the given key and element types.
607 func NewMap(key, elem Type) *Map {
608         return &Map{key: key, elem: elem}
609 }
610
611 // Key returns the key type of map m.
612 func (m *Map) Key() Type { return m.key }
613
614 // Elem returns the element type of map m.
615 func (m *Map) Elem() Type { return m.elem }
616
617 // A Chan represents a channel type.
618 type Chan struct {
619         dir  ChanDir
620         elem Type
621 }
622
623 // A ChanDir value indicates a channel direction.
624 type ChanDir int
625
626 // The direction of a channel is indicated by one of these constants.
627 const (
628         SendRecv ChanDir = iota
629         SendOnly
630         RecvOnly
631 )
632
633 // NewChan returns a new channel type for the given direction and element type.
634 func NewChan(dir ChanDir, elem Type) *Chan {
635         return &Chan{dir: dir, elem: elem}
636 }
637
638 // Dir returns the direction of channel c.
639 func (c *Chan) Dir() ChanDir { return c.dir }
640
641 // Elem returns the element type of channel c.
642 func (c *Chan) Elem() Type { return c.elem }
643
644 // A Named represents a named (defined) type.
645 type Named struct {
646         check      *Checker    // for Named.under implementation
647         info       typeInfo    // for cycle detection
648         obj        *TypeName   // corresponding declared object
649         orig       Type        // type (on RHS of declaration) this *Named type is derived of (for cycle reporting)
650         underlying Type        // possibly a *Named during setup; never a *Named once set up completely
651         tparams    []*TypeName // type parameters, or nil
652         targs      []Type      // type arguments (after instantiation), or nil
653         methods    []*Func     // methods declared for this type (not the method set of this type); signatures are type-checked lazily
654 }
655
656 // NewNamed returns a new named type for the given type name, underlying type, and associated methods.
657 // If the given type name obj doesn't have a type yet, its type is set to the returned named type.
658 // The underlying type must not be a *Named.
659 func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
660         if _, ok := underlying.(*Named); ok {
661                 panic("types.NewNamed: underlying type must not be *Named")
662         }
663         typ := &Named{obj: obj, orig: underlying, underlying: underlying, methods: methods}
664         if obj.typ == nil {
665                 obj.typ = typ
666         }
667         return typ
668 }
669
670 func (check *Checker) NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
671         typ := &Named{check: check, obj: obj, orig: underlying, underlying: underlying, methods: methods}
672         if obj.typ == nil {
673                 obj.typ = typ
674         }
675         return typ
676 }
677
678 // Obj returns the type name for the named type t.
679 func (t *Named) Obj() *TypeName { return t.obj }
680
681 // TODO(gri) Come up with a better representation and API to distinguish
682 //           between parameterized instantiated and non-instantiated types.
683
684 // TParams returns the type parameters of the named type t, or nil.
685 // The result is non-nil for an (originally) parameterized type even if it is instantiated.
686 func (t *Named) TParams() []*TypeName { return t.tparams }
687
688 // TArgs returns the type arguments after instantiation of the named type t, or nil if not instantiated.
689 func (t *Named) TArgs() []Type { return t.targs }
690
691 // SetTArgs sets the type arguments of Named.
692 func (t *Named) SetTArgs(args []Type) { t.targs = args }
693
694 // NumMethods returns the number of explicit methods whose receiver is named type t.
695 func (t *Named) NumMethods() int { return len(t.methods) }
696
697 // Method returns the i'th method of named type t for 0 <= i < t.NumMethods().
698 func (t *Named) Method(i int) *Func { return t.methods[i] }
699
700 // SetUnderlying sets the underlying type and marks t as complete.
701 func (t *Named) SetUnderlying(underlying Type) {
702         if underlying == nil {
703                 panic("types.Named.SetUnderlying: underlying type must not be nil")
704         }
705         if _, ok := underlying.(*Named); ok {
706                 panic("types.Named.SetUnderlying: underlying type must not be *Named")
707         }
708         t.underlying = underlying
709 }
710
711 // AddMethod adds method m unless it is already in the method list.
712 func (t *Named) AddMethod(m *Func) {
713         if i, _ := lookupMethod(t.methods, m.pkg, m.name); i < 0 {
714                 t.methods = append(t.methods, m)
715         }
716 }
717
718 // A TypeParam represents a type parameter type.
719 type TypeParam struct {
720         check *Checker  // for lazy type bound completion
721         id    uint64    // unique id
722         obj   *TypeName // corresponding type name
723         index int       // parameter index
724         bound Type      // *Named or *Interface; underlying type is always *Interface
725 }
726
727 // NewTypeParam returns a new TypeParam.
728 func (check *Checker) NewTypeParam(obj *TypeName, index int, bound Type) *TypeParam {
729         assert(bound != nil)
730         typ := &TypeParam{check: check, id: check.nextId, obj: obj, index: index, bound: bound}
731         check.nextId++
732         if obj.typ == nil {
733                 obj.typ = typ
734         }
735         return typ
736 }
737
738 func (t *TypeParam) Bound() *Interface {
739         iface := asInterface(t.bound)
740         // use the type bound position if we have one
741         pos := token.NoPos
742         if n, _ := t.bound.(*Named); n != nil {
743                 pos = n.obj.pos
744         }
745         // TODO(rFindley) switch this to an unexported method on Checker.
746         t.check.completeInterface(pos, iface)
747         return iface
748 }
749
750 // optype returns a type's operational type. Except for
751 // type parameters, the operational type is the same
752 // as the underlying type (as returned by under). For
753 // Type parameters, the operational type is determined
754 // by the corresponding type bound's type list. The
755 // result may be the bottom or top type, but it is never
756 // the incoming type parameter.
757 func optype(typ Type) Type {
758         if t := asTypeParam(typ); t != nil {
759                 // If the optype is typ, return the top type as we have
760                 // no information. It also prevents infinite recursion
761                 // via the asTypeParam converter function. This can happen
762                 // for a type parameter list of the form:
763                 // (type T interface { type T }).
764                 // See also issue #39680.
765                 if u := t.Bound().allTypes; u != nil && u != typ {
766                         // u != typ and u is a type parameter => under(u) != typ, so this is ok
767                         return under(u)
768                 }
769                 return theTop
770         }
771         return under(typ)
772 }
773
774 // An instance represents an instantiated generic type syntactically
775 // (without expanding the instantiation). Type instances appear only
776 // during type-checking and are replaced by their fully instantiated
777 // (expanded) types before the end of type-checking.
778 type instance struct {
779         check   *Checker    // for lazy instantiation
780         pos     token.Pos   // position of type instantiation; for error reporting only
781         base    *Named      // parameterized type to be instantiated
782         targs   []Type      // type arguments
783         poslist []token.Pos // position of each targ; for error reporting only
784         value   Type        // base(targs...) after instantiation or Typ[Invalid]; nil if not yet set
785 }
786
787 // expand returns the instantiated (= expanded) type of t.
788 // The result is either an instantiated *Named type, or
789 // Typ[Invalid] if there was an error.
790 func (t *instance) expand() Type {
791         v := t.value
792         if v == nil {
793                 v = t.check.instantiate(t.pos, t.base, t.targs, t.poslist)
794                 if v == nil {
795                         v = Typ[Invalid]
796                 }
797                 t.value = v
798         }
799         // After instantiation we must have an invalid or a *Named type.
800         if debug && v != Typ[Invalid] {
801                 _ = v.(*Named)
802         }
803         return v
804 }
805
806 // expand expands a type instance into its instantiated
807 // type and leaves all other types alone. expand does
808 // not recurse.
809 func expand(typ Type) Type {
810         if t, _ := typ.(*instance); t != nil {
811                 return t.expand()
812         }
813         return typ
814 }
815
816 // expandf is set to expand.
817 // Call expandf when calling expand causes compile-time cycle error.
818 var expandf func(Type) Type
819
820 func init() { expandf = expand }
821
822 // bottom represents the bottom of the type lattice.
823 // It is the underlying type of a type parameter that
824 // cannot be satisfied by any type, usually because
825 // the intersection of type constraints left nothing).
826 type bottom struct{}
827
828 // theBottom is the singleton bottom type.
829 var theBottom = &bottom{}
830
831 // top represents the top of the type lattice.
832 // It is the underlying type of a type parameter that
833 // can be satisfied by any type (ignoring methods),
834 // usually because the type constraint has no type
835 // list.
836 type top struct{}
837
838 // theTop is the singleton top type.
839 var theTop = &top{}
840
841 // Type-specific implementations of Underlying.
842 func (t *Basic) Underlying() Type     { return t }
843 func (t *Array) Underlying() Type     { return t }
844 func (t *Slice) Underlying() Type     { return t }
845 func (t *Struct) Underlying() Type    { return t }
846 func (t *Pointer) Underlying() Type   { return t }
847 func (t *Tuple) Underlying() Type     { return t }
848 func (t *Signature) Underlying() Type { return t }
849 func (t *Sum) Underlying() Type       { return t }
850 func (t *Interface) Underlying() Type { return t }
851 func (t *Map) Underlying() Type       { return t }
852 func (t *Chan) Underlying() Type      { return t }
853 func (t *Named) Underlying() Type     { return t.underlying }
854 func (t *TypeParam) Underlying() Type { return t }
855 func (t *instance) Underlying() Type  { return t }
856 func (t *bottom) Underlying() Type    { return t }
857 func (t *top) Underlying() Type       { return t }
858
859 // Type-specific implementations of String.
860 func (t *Basic) String() string     { return TypeString(t, nil) }
861 func (t *Array) String() string     { return TypeString(t, nil) }
862 func (t *Slice) String() string     { return TypeString(t, nil) }
863 func (t *Struct) String() string    { return TypeString(t, nil) }
864 func (t *Pointer) String() string   { return TypeString(t, nil) }
865 func (t *Tuple) String() string     { return TypeString(t, nil) }
866 func (t *Signature) String() string { return TypeString(t, nil) }
867 func (t *Sum) String() string       { return TypeString(t, nil) }
868 func (t *Interface) String() string { return TypeString(t, nil) }
869 func (t *Map) String() string       { return TypeString(t, nil) }
870 func (t *Chan) String() string      { return TypeString(t, nil) }
871 func (t *Named) String() string     { return TypeString(t, nil) }
872 func (t *TypeParam) String() string { return TypeString(t, nil) }
873 func (t *instance) String() string  { return TypeString(t, nil) }
874 func (t *bottom) String() string    { return TypeString(t, nil) }
875 func (t *top) String() string       { return TypeString(t, nil) }
876
877 // under returns the true expanded underlying type.
878 // If it doesn't exist, the result is Typ[Invalid].
879 // under must only be called when a type is known
880 // to be fully set up.
881 func under(t Type) Type {
882         // TODO(gri) is this correct for *Sum?
883         if n := asNamed(t); n != nil {
884                 return n.under()
885         }
886         return t
887 }
888
889 // Converters
890 //
891 // A converter must only be called when a type is
892 // known to be fully set up. A converter returns
893 // a type's operational type (see comment for optype)
894 // or nil if the type argument is not of the
895 // respective type.
896
897 func asBasic(t Type) *Basic {
898         op, _ := optype(t).(*Basic)
899         return op
900 }
901
902 func asArray(t Type) *Array {
903         op, _ := optype(t).(*Array)
904         return op
905 }
906
907 func asSlice(t Type) *Slice {
908         op, _ := optype(t).(*Slice)
909         return op
910 }
911
912 // TODO (rFindley) delete this on the dev.typeparams branch. This is only
913 // exported in the prototype for legacy compatibility.
914 func AsStruct(t Type) *Struct {
915         return asStruct(t)
916 }
917
918 func asStruct(t Type) *Struct {
919         op, _ := optype(t).(*Struct)
920         return op
921 }
922
923 // TODO(rFindley) delete this on the dev.typeparams branch (see ToStruct).
924 func AsPointer(t Type) *Pointer {
925         return asPointer(t)
926 }
927
928 func asPointer(t Type) *Pointer {
929         op, _ := optype(t).(*Pointer)
930         return op
931 }
932
933 func asTuple(t Type) *Tuple {
934         op, _ := optype(t).(*Tuple)
935         return op
936 }
937
938 func asSignature(t Type) *Signature {
939         op, _ := optype(t).(*Signature)
940         return op
941 }
942
943 func asSum(t Type) *Sum {
944         op, _ := optype(t).(*Sum)
945         return op
946 }
947
948 func asInterface(t Type) *Interface {
949         op, _ := optype(t).(*Interface)
950         return op
951 }
952
953 func asMap(t Type) *Map {
954         op, _ := optype(t).(*Map)
955         return op
956 }
957
958 func asChan(t Type) *Chan {
959         op, _ := optype(t).(*Chan)
960         return op
961 }
962
963 // If the argument to asNamed and asTypeParam is of the respective types
964 // (possibly after expanding an instance type), these methods return that type.
965 // Otherwise the result is nil.
966
967 func asNamed(t Type) *Named {
968         e, _ := expand(t).(*Named)
969         return e
970 }
971
972 func asTypeParam(t Type) *TypeParam {
973         u, _ := under(t).(*TypeParam)
974         return u
975 }