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.
10 "go/internal/typeparams"
15 func (check *Checker) interfaceType(ityp *Interface, iface *ast.InterfaceType, def *Named) {
17 var tname *ast.Ident // "type" name of first entry in a type list declaration
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())
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.)
33 check.errorf(name, _BlankIfaceMethod, "invalid method name _")
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
41 // TODO(rfindley) remove once we disallow type lists
42 op := new(ast.UnaryExpr)
45 tlist = append(tlist, op)
46 if tname != nil && tname != name {
47 check.errorf(name, _Todo, "cannot have multiple type lists in an interface")
53 typ := check.typ(f.Type)
54 sig, _ := typ.(*Signature)
56 if typ != Typ[Invalid] {
57 check.invalidAST(f.Type, "%s is not a method signature", typ)
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 {
70 check.errorf(at, _Todo, "methods cannot have type parameters")
73 // use named receiver type if available (for better error messages)
74 var recvTyp Type = ityp
78 sig.recv = NewVar(name.Pos(), check.pkg, "", recvTyp)
80 m := NewFunc(name.Pos(), check.pkg, name.Name, sig)
81 check.recordDef(name, m)
82 ityp.methods = append(ityp.methods, m)
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())
93 if len(ityp.methods) == 0 && len(ityp.embeddeds) == 0 {
95 ityp.allMethods = markComplete
99 // sort for API stability
100 sortMethods(ityp.methods)
101 sortTypes(ityp.embeddeds)
103 check.later(func() { check.completeInterface(iface.Pos(), ityp) })
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)
111 return append(list, x)
114 func (check *Checker) completeInterface(pos token.Pos, ityp *Interface) {
115 if ityp.allMethods != nil {
119 // completeInterface may be called via the LookupFieldOrMethod,
120 // MissingMethod, Identical, or IdenticalIgnoreTags external API
121 // in which case check will be nil. In this case, type-checking
122 // must be finished and all interfaces should have been completed.
124 panic("internal error: incomplete interface")
126 completeInterface(check, pos, ityp)
129 // completeInterface may be called with check == nil.
130 func completeInterface(check *Checker, pos token.Pos, ityp *Interface) {
131 assert(ityp.allMethods == nil)
133 if check != nil && trace {
134 // Types don't generally have position information.
135 // If we don't have a valid pos provided, try to use
137 if !pos.IsValid() && len(ityp.methods) > 0 {
138 pos = ityp.methods[0].pos
141 check.trace(pos, "complete %s", ityp)
145 check.trace(pos, "=> %s (methods = %v, types = %v)", ityp, ityp.allMethods, ityp.allTypes)
149 // An infinitely expanding interface (due to a cycle) is detected
150 // elsewhere (Checker.validType), so here we simply assume we only
151 // have valid interfaces. Mark the interface as complete to avoid
152 // infinite recursion if the validType check occurs later for some
154 ityp.allMethods = markComplete
156 // Methods of embedded interfaces are collected unchanged; i.e., the identity
157 // of a method I.m's Func Object of an interface I is the same as that of
158 // the method m in an interface that embeds interface I. On the other hand,
159 // if a method is embedded via multiple overlapping embedded interfaces, we
160 // don't provide a guarantee which "original m" got chosen for the embedding
161 // interface. See also issue #34421.
163 // If we don't care to provide this identity guarantee anymore, instead of
164 // reusing the original method in embeddings, we can clone the method's Func
165 // Object and give it the position of a corresponding embedded interface. Then
166 // we can get rid of the mpos map below and simply use the cloned method's
172 mpos := make(map[*Func]token.Pos) // method specification or method embedding position, for good error messages
173 addMethod := func(pos token.Pos, m *Func, explicit bool) {
174 switch other := seen.insert(m); {
176 methods = append(methods, m)
180 panic(fmt.Sprintf("%v: duplicate method %s", m.pos, m.name))
183 check.errorf(atPos(pos), _DuplicateDecl, "duplicate method %s", m.name)
184 check.errorf(atPos(mpos[other.(*Func)]), _DuplicateDecl, "\tother declaration of %s", m.name) // secondary error, \t indented
186 // We have a duplicate method name in an embedded (not explicitly declared) method.
187 // Check method signatures after all types are computed (issue #33656).
188 // If we're pre-go1.14 (overlapping embeddings are not permitted), report that
189 // error here as well (even though we could do it eagerly) because it's the same
192 // check method signatures after all locally embedded interfaces are computed
193 todo = append(todo, m, other.(*Func))
198 if !check.allowVersion(m.pkg, 1, 14) || !check.identical(m.typ, other.Type()) {
199 check.errorf(atPos(pos), _DuplicateDecl, "duplicate method %s", m.name)
200 check.errorf(atPos(mpos[other.(*Func)]), _DuplicateDecl, "\tother declaration of %s", m.name) // secondary error, \t indented
206 for _, m := range ityp.methods {
207 addMethod(m.pos, m, true)
210 // collect embedded elements
212 var posList []token.Pos
214 posList = check.posMap[ityp]
216 for i, typ := range ityp.embeddeds {
217 var pos token.Pos // embedding position
222 switch t := under(typ).(type) {
224 if t.allMethods == nil {
225 completeInterface(check, pos, t)
227 for _, m := range t.allMethods {
228 addMethod(pos, m, false) // use embedding position pos rather than m.pos
233 // TODO(gri) combine with default case once we have
234 // converted all tests to new notation and we
235 // can report an error when we don't have an
236 // interface before go1.18.
239 if check != nil && !check.allowVersion(check.pkg, 1, 18) {
240 check.errorf(atPos(pos), _InvalidIfaceEmbed, "%s is a type parameter, not an interface", typ)
245 if typ == Typ[Invalid] {
248 if check != nil && !check.allowVersion(check.pkg, 1, 18) {
249 check.errorf(atPos(pos), _InvalidIfaceEmbed, "%s is not an interface", typ)
254 allTypes = intersect(allTypes, types)
257 // process todo's (this only happens if check == nil)
258 for i := 0; i < len(todo); i += 2 {
261 if !Identical(m.typ, other.typ) {
262 panic(fmt.Sprintf("%v: duplicate method %s", m.pos, m.name))
267 sort.Sort(byUniqueMethodName(methods))
268 ityp.allMethods = methods
270 ityp.allTypes = allTypes
273 func sortTypes(list []Type) {
274 sort.Stable(byUniqueTypeName(list))
277 // byUniqueTypeName named type lists can be sorted by their unique type names.
278 type byUniqueTypeName []Type
280 func (a byUniqueTypeName) Len() int { return len(a) }
281 func (a byUniqueTypeName) Less(i, j int) bool { return sortName(a[i]) < sortName(a[j]) }
282 func (a byUniqueTypeName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
284 func sortName(t Type) string {
285 if named := asNamed(t); named != nil {
286 return named.obj.Id()
291 func sortMethods(list []*Func) {
292 sort.Sort(byUniqueMethodName(list))
295 func assertSortedMethods(list []*Func) {
297 panic("internal error: assertSortedMethods called outside debug mode")
299 if !sort.IsSorted(byUniqueMethodName(list)) {
300 panic("internal error: methods not sorted")
304 // byUniqueMethodName method lists can be sorted by their unique method names.
305 type byUniqueMethodName []*Func
307 func (a byUniqueMethodName) Len() int { return len(a) }
308 func (a byUniqueMethodName) Less(i, j int) bool { return a[i].Id() < a[j].Id() }
309 func (a byUniqueMethodName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }