]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/interface.go
[dev.typeparams] go/types: replace Sum type with Union type
[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         "fmt"
9         "go/ast"
10         "go/internal/typeparams"
11         "go/token"
12         "sort"
13 )
14
15 func (check *Checker) interfaceType(ityp *Interface, iface *ast.InterfaceType, def *Named) {
16         var tlist []ast.Expr
17         var tname *ast.Ident // "type" name of first entry in a type list declaration
18
19         for _, f := range iface.Methods.List {
20                 if len(f.Names) == 0 {
21                         // We have an embedded type; possibly a union of types.
22                         ityp.embeddeds = append(ityp.embeddeds, parseUnion(check, flattenUnion(nil, f.Type)))
23                         check.posMap[ityp] = append(check.posMap[ityp], f.Type.Pos())
24                         continue
25                 }
26
27                 // We have a method with name f.Names[0], or a type
28                 // of a type list (name.Name == "type").
29                 // (The parser ensures that there's only one method
30                 // and we don't care if a constructed AST has more.)
31                 name := f.Names[0]
32                 if name.Name == "_" {
33                         check.errorf(name, _BlankIfaceMethod, "invalid method name _")
34                         continue // ignore
35                 }
36
37                 if name.Name == "type" {
38                         // For now, collect all type list entries as if it
39                         // were a single union, where each union element is
40                         // of the form ~T.
41                         // TODO(rfindley) remove once we disallow type lists
42                         op := new(ast.UnaryExpr)
43                         op.Op = token.TILDE
44                         op.X = f.Type
45                         tlist = append(tlist, op)
46                         if tname != nil && tname != name {
47                                 check.errorf(name, _Todo, "cannot have multiple type lists in an interface")
48                         }
49                         tname = name
50                         continue
51                 }
52
53                 typ := check.typ(f.Type)
54                 sig, _ := typ.(*Signature)
55                 if sig == nil {
56                         if typ != Typ[Invalid] {
57                                 check.invalidAST(f.Type, "%s is not a method signature", typ)
58                         }
59                         continue // ignore
60                 }
61
62                 // Always type-check method type parameters but complain if they are not enabled.
63                 // (This extra check is needed here because interface method signatures don't have
64                 // a receiver specification.)
65                 if sig.tparams != nil {
66                         var at positioner = f.Type
67                         if tparams := typeparams.Get(f.Type); tparams != nil {
68                                 at = tparams
69                         }
70                         check.errorf(at, _Todo, "methods cannot have type parameters")
71                 }
72
73                 // use named receiver type if available (for better error messages)
74                 var recvTyp Type = ityp
75                 if def != nil {
76                         recvTyp = def
77                 }
78                 sig.recv = NewVar(name.Pos(), check.pkg, "", recvTyp)
79
80                 m := NewFunc(name.Pos(), check.pkg, name.Name, sig)
81                 check.recordDef(name, m)
82                 ityp.methods = append(ityp.methods, m)
83         }
84
85         // type constraints
86         if tlist != nil {
87                 ityp.embeddeds = append(ityp.embeddeds, parseUnion(check, tlist))
88                 // Types T in a type list are added as ~T expressions but we don't
89                 // have the position of the '~'. Use the first type position instead.
90                 check.posMap[ityp] = append(check.posMap[ityp], tlist[0].(*ast.UnaryExpr).X.Pos())
91         }
92
93         if len(ityp.methods) == 0 && len(ityp.embeddeds) == 0 {
94                 // empty interface
95                 ityp.allMethods = markComplete
96                 return
97         }
98
99         // sort for API stability
100         sortMethods(ityp.methods)
101         sortTypes(ityp.embeddeds)
102
103         check.later(func() { check.completeInterface(iface.Pos(), ityp) })
104 }
105
106 func flattenUnion(list []ast.Expr, x ast.Expr) []ast.Expr {
107         if o, _ := x.(*ast.BinaryExpr); o != nil && o.Op == token.OR {
108                 list = flattenUnion(list, o.X)
109                 x = o.Y
110         }
111         return append(list, x)
112 }
113
114 // includes reports whether typ is in list.
115 func includes(list []Type, typ Type) bool {
116         for _, e := range list {
117                 if Identical(typ, e) {
118                         return true
119                 }
120         }
121         return false
122 }
123
124 func (check *Checker) completeInterface(pos token.Pos, ityp *Interface) {
125         if ityp.allMethods != nil {
126                 return
127         }
128
129         // completeInterface may be called via the LookupFieldOrMethod,
130         // MissingMethod, Identical, or IdenticalIgnoreTags external API
131         // in which case check will be nil. In this case, type-checking
132         // must be finished and all interfaces should have been completed.
133         if check == nil {
134                 panic("internal error: incomplete interface")
135         }
136         completeInterface(check, pos, ityp)
137 }
138
139 // completeInterface may be called with check == nil.
140 func completeInterface(check *Checker, pos token.Pos, ityp *Interface) {
141         assert(ityp.allMethods == nil)
142
143         if check != nil && trace {
144                 // Types don't generally have position information.
145                 // If we don't have a valid pos provided, try to use
146                 // one close enough.
147                 if !pos.IsValid() && len(ityp.methods) > 0 {
148                         pos = ityp.methods[0].pos
149                 }
150
151                 check.trace(pos, "complete %s", ityp)
152                 check.indent++
153                 defer func() {
154                         check.indent--
155                         check.trace(pos, "=> %s (methods = %v, types = %v)", ityp, ityp.allMethods, ityp.allTypes)
156                 }()
157         }
158
159         // An infinitely expanding interface (due to a cycle) is detected
160         // elsewhere (Checker.validType), so here we simply assume we only
161         // have valid interfaces. Mark the interface as complete to avoid
162         // infinite recursion if the validType check occurs later for some
163         // reason.
164         ityp.allMethods = markComplete
165
166         // Methods of embedded interfaces are collected unchanged; i.e., the identity
167         // of a method I.m's Func Object of an interface I is the same as that of
168         // the method m in an interface that embeds interface I. On the other hand,
169         // if a method is embedded via multiple overlapping embedded interfaces, we
170         // don't provide a guarantee which "original m" got chosen for the embedding
171         // interface. See also issue #34421.
172         //
173         // If we don't care to provide this identity guarantee anymore, instead of
174         // reusing the original method in embeddings, we can clone the method's Func
175         // Object and give it the position of a corresponding embedded interface. Then
176         // we can get rid of the mpos map below and simply use the cloned method's
177         // position.
178
179         var todo []*Func
180         var seen objset
181         var methods []*Func
182         mpos := make(map[*Func]token.Pos) // method specification or method embedding position, for good error messages
183         addMethod := func(pos token.Pos, m *Func, explicit bool) {
184                 switch other := seen.insert(m); {
185                 case other == nil:
186                         methods = append(methods, m)
187                         mpos[m] = pos
188                 case explicit:
189                         if check == nil {
190                                 panic(fmt.Sprintf("%v: duplicate method %s", m.pos, m.name))
191                         }
192                         // check != nil
193                         check.errorf(atPos(pos), _DuplicateDecl, "duplicate method %s", m.name)
194                         check.errorf(atPos(mpos[other.(*Func)]), _DuplicateDecl, "\tother declaration of %s", m.name) // secondary error, \t indented
195                 default:
196                         // We have a duplicate method name in an embedded (not explicitly declared) method.
197                         // Check method signatures after all types are computed (issue #33656).
198                         // If we're pre-go1.14 (overlapping embeddings are not permitted), report that
199                         // error here as well (even though we could do it eagerly) because it's the same
200                         // error message.
201                         if check == nil {
202                                 // check method signatures after all locally embedded interfaces are computed
203                                 todo = append(todo, m, other.(*Func))
204                                 break
205                         }
206                         // check != nil
207                         check.later(func() {
208                                 if !check.allowVersion(m.pkg, 1, 14) || !check.identical(m.typ, other.Type()) {
209                                         check.errorf(atPos(pos), _DuplicateDecl, "duplicate method %s", m.name)
210                                         check.errorf(atPos(mpos[other.(*Func)]), _DuplicateDecl, "\tother declaration of %s", m.name) // secondary error, \t indented
211                                 }
212                         })
213                 }
214         }
215
216         for _, m := range ityp.methods {
217                 addMethod(m.pos, m, true)
218         }
219
220         // collect embedded elements
221         var allTypes Type
222         var posList []token.Pos
223         if check != nil {
224                 posList = check.posMap[ityp]
225         }
226         for i, typ := range ityp.embeddeds {
227                 var pos token.Pos // embedding position
228                 if posList != nil {
229                         pos = posList[i]
230                 }
231                 var types Type
232                 switch t := under(typ).(type) {
233                 case *Interface:
234                         if t.allMethods == nil {
235                                 completeInterface(check, pos, t)
236                         }
237                         for _, m := range t.allMethods {
238                                 addMethod(pos, m, false) // use embedding position pos rather than m.pos
239
240                         }
241                         types = t.allTypes
242                 case *Union:
243                         // TODO(gri) combine with default case once we have
244                         //           converted all tests to new notation and we
245                         //           can report an error when we don't have an
246                         //           interface before go1.18.
247                         types = typ
248                 case *TypeParam:
249                         if check != nil && !check.allowVersion(check.pkg, 1, 18) {
250                                 check.errorf(atPos(pos), _InvalidIfaceEmbed, "%s is a type parameter, not an interface", typ)
251                                 continue
252                         }
253                         types = typ
254                 default:
255                         if typ == Typ[Invalid] {
256                                 continue
257                         }
258                         if check != nil && !check.allowVersion(check.pkg, 1, 18) {
259                                 check.errorf(atPos(pos), _InvalidIfaceEmbed, "%s is not an interface", typ)
260                                 continue
261                         }
262                         types = typ
263                 }
264                 allTypes = intersect(allTypes, types)
265         }
266
267         // process todo's (this only happens if check == nil)
268         for i := 0; i < len(todo); i += 2 {
269                 m := todo[i]
270                 other := todo[i+1]
271                 if !Identical(m.typ, other.typ) {
272                         panic(fmt.Sprintf("%v: duplicate method %s", m.pos, m.name))
273                 }
274         }
275
276         if methods != nil {
277                 sort.Sort(byUniqueMethodName(methods))
278                 ityp.allMethods = methods
279         }
280         ityp.allTypes = allTypes
281 }
282
283 func sortTypes(list []Type) {
284         sort.Stable(byUniqueTypeName(list))
285 }
286
287 // byUniqueTypeName named type lists can be sorted by their unique type names.
288 type byUniqueTypeName []Type
289
290 func (a byUniqueTypeName) Len() int           { return len(a) }
291 func (a byUniqueTypeName) Less(i, j int) bool { return sortName(a[i]) < sortName(a[j]) }
292 func (a byUniqueTypeName) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
293
294 func sortName(t Type) string {
295         if named := asNamed(t); named != nil {
296                 return named.obj.Id()
297         }
298         return ""
299 }
300
301 func sortMethods(list []*Func) {
302         sort.Sort(byUniqueMethodName(list))
303 }
304
305 func assertSortedMethods(list []*Func) {
306         if !debug {
307                 panic("internal error: assertSortedMethods called outside debug mode")
308         }
309         if !sort.IsSorted(byUniqueMethodName(list)) {
310                 panic("internal error: methods not sorted")
311         }
312 }
313
314 // byUniqueMethodName method lists can be sorted by their unique method names.
315 type byUniqueMethodName []*Func
316
317 func (a byUniqueMethodName) Len() int           { return len(a) }
318 func (a byUniqueMethodName) Less(i, j int) bool { return a[i].Id() < a[j].Id() }
319 func (a byUniqueMethodName) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }