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) {
16 var tlist *ast.Ident // "type" name of first entry in a type list declaration
18 for _, f := range iface.Methods.List {
20 // We have a method with name f.Names[0], or a type
21 // of a type list (name.Name == "type").
22 // (The parser ensures that there's only one method
23 // and we don't care if a constructed AST has more.)
26 check.errorf(name, _BlankIfaceMethod, "invalid method name _")
30 if name.Name == "type" {
31 // Always collect all type list entries, even from
32 // different type lists, under the assumption that
33 // the author intended to include all types.
34 types = append(types, f.Type)
35 if tlist != nil && tlist != name {
36 check.errorf(name, _Todo, "cannot have multiple type lists in an interface")
42 typ := check.typ(f.Type)
43 sig, _ := typ.(*Signature)
45 if typ != Typ[Invalid] {
46 check.invalidAST(f.Type, "%s is not a method signature", typ)
51 // Always type-check method type parameters but complain if they are not enabled.
52 // (This extra check is needed here because interface method signatures don't have
53 // a receiver specification.)
54 if sig.tparams != nil {
55 var at positioner = f.Type
56 if tparams := typeparams.Get(f.Type); tparams != nil {
59 check.errorf(at, _Todo, "methods cannot have type parameters")
62 // use named receiver type if available (for better error messages)
63 var recvTyp Type = ityp
67 sig.recv = NewVar(name.Pos(), check.pkg, "", recvTyp)
69 m := NewFunc(name.Pos(), check.pkg, name.Name, sig)
70 check.recordDef(name, m)
71 ityp.methods = append(ityp.methods, m)
73 // We have an embedded type. completeInterface will
74 // eventually verify that we have an interface.
75 ityp.embeddeds = append(ityp.embeddeds, check.typ(f.Type))
76 check.posMap[ityp] = append(check.posMap[ityp], f.Type.Pos())
81 ityp.types = _NewSum(check.collectTypeConstraints(iface.Pos(), types))
83 if len(ityp.methods) == 0 && ityp.types == nil && len(ityp.embeddeds) == 0 {
85 ityp.allMethods = markComplete
89 // sort for API stability
90 sortMethods(ityp.methods)
91 sortTypes(ityp.embeddeds)
93 check.later(func() { check.completeInterface(iface.Pos(), ityp) })
96 func (check *Checker) collectTypeConstraints(pos token.Pos, types []ast.Expr) []Type {
97 list := make([]Type, 0, len(types)) // assume all types are correct
98 for _, texpr := range types {
100 check.invalidAST(atPos(pos), "missing type constraint")
103 list = append(list, check.varType(texpr))
106 // Ensure that each type is only present once in the type list. Types may be
107 // interfaces, which may not be complete yet. It's ok to do this check at the
108 // end because it's not a requirement for correctness of the code.
109 // Note: This is a quadratic algorithm, but type lists tend to be short.
111 for i, t := range list {
112 if t := asInterface(t); t != nil {
113 check.completeInterface(types[i].Pos(), t)
115 if includes(list[:i], t) {
116 check.softErrorf(types[i], _Todo, "duplicate type %s in type list", t)
124 // includes reports whether typ is in list.
125 func includes(list []Type, typ Type) bool {
126 for _, e := range list {
127 if Identical(typ, e) {
134 func (check *Checker) completeInterface(pos token.Pos, ityp *Interface) {
135 if ityp.allMethods != nil {
139 // completeInterface may be called via the LookupFieldOrMethod,
140 // MissingMethod, Identical, or IdenticalIgnoreTags external API
141 // in which case check will be nil. In this case, type-checking
142 // must be finished and all interfaces should have been completed.
144 panic("internal error: incomplete interface")
146 completeInterface(check, pos, ityp)
149 func completeInterface(check *Checker, pos token.Pos, ityp *Interface) {
150 assert(ityp.allMethods == nil)
152 if check != nil && trace {
153 // Types don't generally have position information.
154 // If we don't have a valid pos provided, try to use
156 if !pos.IsValid() && len(ityp.methods) > 0 {
157 pos = ityp.methods[0].pos
160 check.trace(pos, "complete %s", ityp)
164 check.trace(pos, "=> %s (methods = %v, types = %v)", ityp, ityp.allMethods, ityp.allTypes)
168 // An infinitely expanding interface (due to a cycle) is detected
169 // elsewhere (Checker.validType), so here we simply assume we only
170 // have valid interfaces. Mark the interface as complete to avoid
171 // infinite recursion if the validType check occurs later for some
173 ityp.allMethods = markComplete
175 // Methods of embedded interfaces are collected unchanged; i.e., the identity
176 // of a method I.m's Func Object of an interface I is the same as that of
177 // the method m in an interface that embeds interface I. On the other hand,
178 // if a method is embedded via multiple overlapping embedded interfaces, we
179 // don't provide a guarantee which "original m" got chosen for the embedding
180 // interface. See also issue #34421.
182 // If we don't care to provide this identity guarantee anymore, instead of
183 // reusing the original method in embeddings, we can clone the method's Func
184 // Object and give it the position of a corresponding embedded interface. Then
185 // we can get rid of the mpos map below and simply use the cloned method's
191 mpos := make(map[*Func]token.Pos) // method specification or method embedding position, for good error messages
192 addMethod := func(pos token.Pos, m *Func, explicit bool) {
193 switch other := seen.insert(m); {
195 methods = append(methods, m)
199 panic(fmt.Sprintf("%v: duplicate method %s", m.pos, m.name))
201 check.errorf(atPos(pos), _DuplicateDecl, "duplicate method %s", m.name)
202 check.errorf(atPos(mpos[other.(*Func)]), _DuplicateDecl, "\tother declaration of %s", m.name) // secondary error, \t indented
204 // We have a duplicate method name in an embedded (not explicitly declared) method.
205 // Check method signatures after all types are computed (issue #33656).
206 // If we're pre-go1.14 (overlapping embeddings are not permitted), report that
207 // error here as well (even though we could do it eagerly) because it's the same
210 // check method signatures after all locally embedded interfaces are computed
211 todo = append(todo, m, other.(*Func))
215 if !check.allowVersion(m.pkg, 1, 14) || !check.identical(m.typ, other.Type()) {
216 check.errorf(atPos(pos), _DuplicateDecl, "duplicate method %s", m.name)
217 check.errorf(atPos(mpos[other.(*Func)]), _DuplicateDecl, "\tother declaration of %s", m.name) // secondary error, \t indented
223 for _, m := range ityp.methods {
224 addMethod(m.pos, m, true)
228 allTypes := ityp.types
230 var posList []token.Pos
232 posList = check.posMap[ityp]
234 for i, typ := range ityp.embeddeds {
235 var pos token.Pos // embedding position
240 etyp := asInterface(utyp)
242 if utyp != Typ[Invalid] {
244 if _, ok := utyp.(*_TypeParam); ok {
245 format = "%s is a type parameter, not an interface"
247 format = "%s is not an interface"
250 // TODO: correct error code.
251 check.errorf(atPos(pos), _InvalidIfaceEmbed, format, typ)
253 panic(fmt.Sprintf(format, typ))
258 if etyp.allMethods == nil {
259 completeInterface(check, pos, etyp)
261 for _, m := range etyp.allMethods {
262 addMethod(pos, m, false) // use embedding position pos rather than m.pos
264 allTypes = intersect(allTypes, etyp.allTypes)
267 // process todo's (this only happens if check == nil)
268 for i := 0; i < len(todo); i += 2 {
271 if !Identical(m.typ, other.typ) {
272 panic(fmt.Sprintf("%v: duplicate method %s", m.pos, m.name))
277 sort.Sort(byUniqueMethodName(methods))
278 ityp.allMethods = methods
280 ityp.allTypes = allTypes
283 // intersect computes the intersection of the types x and y.
284 // Note: A incomming nil type stands for the top type. A top
285 // type result is returned as nil.
286 func intersect(x, y Type) (r Type) {
294 case x == theBottom || y == theBottom:
296 case x == nil || x == theTop:
298 case y == nil || x == theTop:
302 xtypes := unpackType(x)
303 ytypes := unpackType(y)
304 // Compute the list rtypes which includes only
305 // types that are in both xtypes and ytypes.
306 // Quadratic algorithm, but good enough for now.
307 // TODO(gri) fix this
309 for _, x := range xtypes {
310 if includes(ytypes, x) {
311 rtypes = append(rtypes, x)
318 return _NewSum(rtypes)
321 func sortTypes(list []Type) {
322 sort.Stable(byUniqueTypeName(list))
325 // byUniqueTypeName named type lists can be sorted by their unique type names.
326 type byUniqueTypeName []Type
328 func (a byUniqueTypeName) Len() int { return len(a) }
329 func (a byUniqueTypeName) Less(i, j int) bool { return sortName(a[i]) < sortName(a[j]) }
330 func (a byUniqueTypeName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
332 func sortName(t Type) string {
333 if named := asNamed(t); named != nil {
334 return named.obj.Id()
339 func sortMethods(list []*Func) {
340 sort.Sort(byUniqueMethodName(list))
343 func assertSortedMethods(list []*Func) {
345 panic("internal error: assertSortedMethods called outside debug mode")
347 if !sort.IsSorted(byUniqueMethodName(list)) {
348 panic("internal error: methods not sorted")
352 // byUniqueMethodName method lists can be sorted by their unique method names.
353 type byUniqueMethodName []*Func
355 func (a byUniqueMethodName) Len() int { return len(a) }
356 func (a byUniqueMethodName) Less(i, j int) bool { return a[i].Id() < a[j].Id() }
357 func (a byUniqueMethodName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }