]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/interface.go
[dev.typeparams] go/types: use type terms to represent unions
[gostls13.git] / src / go / types / interface.go
1 // Copyright 2021 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         "go/ast"
9         "go/internal/typeparams"
10         "go/token"
11 )
12
13 // ----------------------------------------------------------------------------
14 // API
15
16 // An Interface represents an interface type.
17 type Interface struct {
18         obj       *TypeName    // type name object defining this interface; or nil (for better error messages)
19         methods   []*Func      // ordered list of explicitly declared methods
20         embeddeds []Type       // ordered list of explicitly embedded elements
21         embedPos  *[]token.Pos // positions of embedded elements; or nil (for error messages) - use pointer to save space
22         complete  bool         // indicates that obj, methods, and embeddeds are set and type set can be computed
23
24         tset *TypeSet // type set described by this interface, computed lazily
25 }
26
27 // typeSet returns the type set for interface t.
28 func (t *Interface) typeSet() *TypeSet { return computeTypeSet(nil, token.NoPos, t) }
29
30 // is reports whether interface t represents types that all satisfy f.
31 func (t *Interface) is(f func(Type, bool) bool) bool {
32         switch t := t.typeSet().types.(type) {
33         case nil, *top:
34                 // TODO(gri) should settle on top or nil to represent this case
35                 return false // we must have at least one type! (was bug)
36         case *Union:
37                 return t.is(func(t *term) bool { return f(t.typ, t.tilde) })
38         default:
39                 return f(t, false)
40         }
41 }
42
43 // emptyInterface represents the empty (completed) interface
44 var emptyInterface = Interface{complete: true, tset: &topTypeSet}
45
46 // NewInterface returns a new interface for the given methods and embedded types.
47 // NewInterface takes ownership of the provided methods and may modify their types
48 // by setting missing receivers.
49 //
50 // Deprecated: Use NewInterfaceType instead which allows arbitrary embedded types.
51 func NewInterface(methods []*Func, embeddeds []*Named) *Interface {
52         tnames := make([]Type, len(embeddeds))
53         for i, t := range embeddeds {
54                 tnames[i] = t
55         }
56         return NewInterfaceType(methods, tnames)
57 }
58
59 // NewInterfaceType returns a new interface for the given methods and embedded types.
60 // NewInterfaceType takes ownership of the provided methods and may modify their types
61 // by setting missing receivers.
62 func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface {
63         if len(methods) == 0 && len(embeddeds) == 0 {
64                 return &emptyInterface
65         }
66
67         // set method receivers if necessary
68         typ := new(Interface)
69         for _, m := range methods {
70                 if sig := m.typ.(*Signature); sig.recv == nil {
71                         sig.recv = NewVar(m.pos, m.pkg, "", typ)
72                 }
73         }
74
75         // sort for API stability
76         sortMethods(methods)
77
78         typ.methods = methods
79         typ.embeddeds = embeddeds
80         typ.complete = true
81
82         return typ
83 }
84
85 // NumExplicitMethods returns the number of explicitly declared methods of interface t.
86 func (t *Interface) NumExplicitMethods() int { return len(t.methods) }
87
88 // ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods().
89 // The methods are ordered by their unique Id.
90 func (t *Interface) ExplicitMethod(i int) *Func { return t.methods[i] }
91
92 // NumEmbeddeds returns the number of embedded types in interface t.
93 func (t *Interface) NumEmbeddeds() int { return len(t.embeddeds) }
94
95 // Embedded returns the i'th embedded defined (*Named) type of interface t for 0 <= i < t.NumEmbeddeds().
96 // The result is nil if the i'th embedded type is not a defined type.
97 //
98 // Deprecated: Use EmbeddedType which is not restricted to defined (*Named) types.
99 func (t *Interface) Embedded(i int) *Named { tname, _ := t.embeddeds[i].(*Named); return tname }
100
101 // EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().
102 func (t *Interface) EmbeddedType(i int) Type { return t.embeddeds[i] }
103
104 // NumMethods returns the total number of methods of interface t.
105 func (t *Interface) NumMethods() int { return t.typeSet().NumMethods() }
106
107 // Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
108 // The methods are ordered by their unique Id.
109 func (t *Interface) Method(i int) *Func { return t.typeSet().Method(i) }
110
111 // Empty reports whether t is the empty interface.
112 func (t *Interface) Empty() bool { return t.typeSet().IsTop() }
113
114 // IsComparable reports whether each type in interface t's type set is comparable.
115 func (t *Interface) IsComparable() bool { return t.typeSet().IsComparable() }
116
117 // IsConstraint reports whether interface t is not just a method set.
118 func (t *Interface) IsConstraint() bool { return !t.typeSet().IsMethodSet() }
119
120 // isSatisfiedBy reports whether interface t's type list is satisfied by the type typ.
121 // If the type list is empty (absent), typ trivially satisfies the interface.
122 // TODO(gri) This is not a great name. Eventually, we should have a more comprehensive
123 //           "implements" predicate.
124 func (t *Interface) isSatisfiedBy(typ Type) bool {
125         t.Complete()
126         switch t := t.typeSet().types.(type) {
127         case nil:
128                 return true // no type restrictions
129         case *Union:
130                 r, _ := t.intersect(typ, false)
131                 return r != nil
132         default:
133                 return Identical(t, typ)
134         }
135 }
136
137 // Complete computes the interface's type set. It must be called by users of
138 // NewInterfaceType and NewInterface after the interface's embedded types are
139 // fully defined and before using the interface type in any way other than to
140 // form other types. The interface must not contain duplicate methods or a
141 // panic occurs. Complete returns the receiver.
142 //
143 // Deprecated: Type sets are now computed lazily, on demand; this function
144 //             is only here for backward-compatibility. It does not have to
145 //             be called explicitly anymore.
146 func (t *Interface) Complete() *Interface {
147         // Some tests are still depending on the state change
148         // (string representation of an Interface not containing an
149         // /* incomplete */ marker) caused by the explicit Complete
150         // call, so we compute the type set eagerly here.
151         t.complete = true
152         t.typeSet()
153         return t
154 }
155
156 func (t *Interface) Underlying() Type { return t }
157 func (t *Interface) String() string   { return TypeString(t, nil) }
158
159 // ----------------------------------------------------------------------------
160 // Implementation
161
162 func (check *Checker) interfaceType(ityp *Interface, iface *ast.InterfaceType, def *Named) {
163         var tlist []ast.Expr
164         var tname *ast.Ident // "type" name of first entry in a type list declaration
165
166         addEmbedded := func(pos token.Pos, typ Type) {
167                 ityp.embeddeds = append(ityp.embeddeds, typ)
168                 if ityp.embedPos == nil {
169                         ityp.embedPos = new([]token.Pos)
170                 }
171                 *ityp.embedPos = append(*ityp.embedPos, pos)
172         }
173
174         for _, f := range iface.Methods.List {
175                 if len(f.Names) == 0 {
176                         // We have an embedded type; possibly a union of types.
177                         addEmbedded(f.Type.Pos(), parseUnion(check, flattenUnion(nil, f.Type)))
178                         continue
179                 }
180
181                 // We have a method with name f.Names[0], or a type
182                 // of a type list (name.Name == "type").
183                 // (The parser ensures that there's only one method
184                 // and we don't care if a constructed AST has more.)
185                 name := f.Names[0]
186                 if name.Name == "_" {
187                         check.errorf(name, _BlankIfaceMethod, "invalid method name _")
188                         continue // ignore
189                 }
190
191                 // TODO(rfindley) Remove type list handling once the parser doesn't accept type lists anymore.
192                 if name.Name == "type" {
193                         // Report an error for the first type list per interface
194                         // if we don't allow type lists, but continue.
195                         if !allowTypeLists && tlist == nil {
196                                 check.softErrorf(name, _Todo, "use generalized embedding syntax instead of a type list")
197                         }
198                         // For now, collect all type list entries as if it
199                         // were a single union, where each union element is
200                         // of the form ~T.
201                         // TODO(rfindley) remove once we disallow type lists
202                         op := new(ast.UnaryExpr)
203                         op.Op = token.TILDE
204                         op.X = f.Type
205                         tlist = append(tlist, op)
206                         // Report an error if we have multiple type lists in an
207                         // interface, but only if they are permitted in the first place.
208                         if allowTypeLists && tname != nil && tname != name {
209                                 check.errorf(name, _Todo, "cannot have multiple type lists in an interface")
210                         }
211                         tname = name
212                         continue
213                 }
214
215                 typ := check.typ(f.Type)
216                 sig, _ := typ.(*Signature)
217                 if sig == nil {
218                         if typ != Typ[Invalid] {
219                                 check.invalidAST(f.Type, "%s is not a method signature", typ)
220                         }
221                         continue // ignore
222                 }
223
224                 // Always type-check method type parameters but complain if they are not enabled.
225                 // (This extra check is needed here because interface method signatures don't have
226                 // a receiver specification.)
227                 if sig.tparams != nil {
228                         var at positioner = f.Type
229                         if tparams := typeparams.Get(f.Type); tparams != nil {
230                                 at = tparams
231                         }
232                         check.errorf(at, _Todo, "methods cannot have type parameters")
233                 }
234
235                 // use named receiver type if available (for better error messages)
236                 var recvTyp Type = ityp
237                 if def != nil {
238                         recvTyp = def
239                 }
240                 sig.recv = NewVar(name.Pos(), check.pkg, "", recvTyp)
241
242                 m := NewFunc(name.Pos(), check.pkg, name.Name, sig)
243                 check.recordDef(name, m)
244                 ityp.methods = append(ityp.methods, m)
245         }
246
247         // type constraints
248         if tlist != nil {
249                 // TODO(rfindley): this differs from types2 due to the use of Pos() below,
250                 // which should actually be on the ~. Confirm that this position is correct.
251                 addEmbedded(tlist[0].Pos(), parseUnion(check, tlist))
252         }
253
254         // All methods and embedded elements for this interface are collected;
255         // i.e., this interface is may be used in a type set computation.
256         ityp.complete = true
257
258         if len(ityp.methods) == 0 && len(ityp.embeddeds) == 0 {
259                 // empty interface
260                 ityp.tset = &topTypeSet
261                 return
262         }
263
264         // sort for API stability
265         sortMethods(ityp.methods)
266         // (don't sort embeddeds: they must correspond to *embedPos entries)
267
268         // Compute type set with a non-nil *Checker as soon as possible
269         // to report any errors. Subsequent uses of type sets will use
270         // this computed type set and won't need to pass in a *Checker.
271         check.later(func() { computeTypeSet(check, iface.Pos(), ityp) })
272 }
273
274 func flattenUnion(list []ast.Expr, x ast.Expr) []ast.Expr {
275         if o, _ := x.(*ast.BinaryExpr); o != nil && o.Op == token.OR {
276                 list = flattenUnion(list, o.X)
277                 x = o.Y
278         }
279         return append(list, x)
280 }