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