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.
12 // ----------------------------------------------------------------------------
15 // An Interface represents an interface type.
16 type Interface struct {
17 check *Checker // for error reporting; nil once type set is computed
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
24 tset *_TypeSet // type set described by this interface, computed lazily
27 // typeSet returns the type set for interface t.
28 func (t *Interface) typeSet() *_TypeSet { return computeInterfaceTypeSet(t.check, token.NoPos, t) }
30 // emptyInterface represents the empty (completed) interface
31 var emptyInterface = Interface{complete: true, tset: &topTypeSet}
33 // NewInterface returns a new interface for the given methods and embedded types.
34 // NewInterface takes ownership of the provided methods and may modify their types
35 // by setting missing receivers.
37 // Deprecated: Use NewInterfaceType instead which allows arbitrary embedded types.
38 func NewInterface(methods []*Func, embeddeds []*Named) *Interface {
39 tnames := make([]Type, len(embeddeds))
40 for i, t := range embeddeds {
43 return NewInterfaceType(methods, tnames)
46 // NewInterfaceType returns a new interface for the given methods and embedded
47 // types. NewInterfaceType takes ownership of the provided methods and may
48 // modify their types by setting missing receivers.
50 // To avoid race conditions, the interface's type set should be computed before
51 // concurrent use of the interface, by explicitly calling Complete.
52 func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface {
53 if len(methods) == 0 && len(embeddeds) == 0 {
54 return &emptyInterface
57 // set method receivers if necessary
59 for _, m := range methods {
60 if sig := m.typ.(*Signature); sig.recv == nil {
61 sig.recv = NewVar(m.pos, m.pkg, "", typ)
65 // sort for API stability
69 typ.embeddeds = embeddeds
75 // NumExplicitMethods returns the number of explicitly declared methods of interface t.
76 func (t *Interface) NumExplicitMethods() int { return len(t.methods) }
78 // ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods().
79 // The methods are ordered by their unique Id.
80 func (t *Interface) ExplicitMethod(i int) *Func { return t.methods[i] }
82 // NumEmbeddeds returns the number of embedded types in interface t.
83 func (t *Interface) NumEmbeddeds() int { return len(t.embeddeds) }
85 // Embedded returns the i'th embedded defined (*Named) type of interface t for 0 <= i < t.NumEmbeddeds().
86 // The result is nil if the i'th embedded type is not a defined type.
88 // Deprecated: Use EmbeddedType which is not restricted to defined (*Named) types.
89 func (t *Interface) Embedded(i int) *Named { tname, _ := t.embeddeds[i].(*Named); return tname }
91 // EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().
92 func (t *Interface) EmbeddedType(i int) Type { return t.embeddeds[i] }
94 // NumMethods returns the total number of methods of interface t.
95 func (t *Interface) NumMethods() int { return t.typeSet().NumMethods() }
97 // Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
98 // The methods are ordered by their unique Id.
99 func (t *Interface) Method(i int) *Func { return t.typeSet().Method(i) }
101 // Empty reports whether t is the empty interface.
102 func (t *Interface) Empty() bool { return t.typeSet().IsAll() }
104 // IsComparable reports whether each type in interface t's type set is comparable.
105 func (t *Interface) IsComparable() bool { return t.typeSet().IsComparable() }
107 // IsMethodSet reports whether the interface t is fully described by its method
109 func (t *Interface) IsMethodSet() bool { return t.typeSet().IsMethodSet() }
111 // Complete computes the interface's type set. It must be called by users of
112 // NewInterfaceType and NewInterface after the interface's embedded types are
113 // fully defined and before using the interface type in any way other than to
114 // form other types. The interface must not contain duplicate methods or a
115 // panic occurs. Complete returns the receiver.
117 // Interface types that have been completed are safe for concurrent use.
118 func (t *Interface) Complete() *Interface {
122 t.typeSet() // checks if t.tset is already set
126 func (t *Interface) Underlying() Type { return t }
127 func (t *Interface) String() string { return TypeString(t, nil) }
129 // ----------------------------------------------------------------------------
132 func (check *Checker) interfaceType(ityp *Interface, iface *ast.InterfaceType, def *Named) {
134 var tname *ast.Ident // "type" name of first entry in a type list declaration
136 addEmbedded := func(pos token.Pos, typ Type) {
137 ityp.embeddeds = append(ityp.embeddeds, typ)
138 if ityp.embedPos == nil {
139 ityp.embedPos = new([]token.Pos)
141 *ityp.embedPos = append(*ityp.embedPos, pos)
144 for _, f := range iface.Methods.List {
145 if len(f.Names) == 0 {
146 // We have an embedded type; possibly a union of types.
147 addEmbedded(f.Type.Pos(), parseUnion(check, flattenUnion(nil, f.Type)))
151 // We have a method with name f.Names[0], or a type
152 // of a type list (name.Name == "type").
153 // (The parser ensures that there's only one method
154 // and we don't care if a constructed AST has more.)
156 if name.Name == "_" {
157 check.errorf(name, _BlankIfaceMethod, "invalid method name _")
161 // TODO(rfindley) Remove type list handling once the parser doesn't accept type lists anymore.
162 if name.Name == "type" {
163 // Report an error for the first type list per interface
164 // if we don't allow type lists, but continue.
165 if !allowTypeLists && tlist == nil {
166 check.softErrorf(name, _Todo, "use generalized embedding syntax instead of a type list")
168 // For now, collect all type list entries as if it
169 // were a single union, where each union element is
171 // TODO(rfindley) remove once we disallow type lists
172 op := new(ast.UnaryExpr)
175 tlist = append(tlist, op)
176 // Report an error if we have multiple type lists in an
177 // interface, but only if they are permitted in the first place.
178 if allowTypeLists && tname != nil && tname != name {
179 check.errorf(name, _Todo, "cannot have multiple type lists in an interface")
185 typ := check.typ(f.Type)
186 sig, _ := typ.(*Signature)
188 if typ != Typ[Invalid] {
189 check.invalidAST(f.Type, "%s is not a method signature", typ)
194 // Always type-check method type parameters but complain if they are not enabled.
195 // (This extra check is needed here because interface method signatures don't have
196 // a receiver specification.)
197 if sig.tparams != nil {
198 var at positioner = f.Type
199 if ftyp, _ := f.Type.(*ast.FuncType); ftyp != nil && ftyp.TypeParams != nil {
202 check.errorf(at, _Todo, "methods cannot have type parameters")
205 // use named receiver type if available (for better error messages)
206 var recvTyp Type = ityp
210 sig.recv = NewVar(name.Pos(), check.pkg, "", recvTyp)
212 m := NewFunc(name.Pos(), check.pkg, name.Name, sig)
213 check.recordDef(name, m)
214 ityp.methods = append(ityp.methods, m)
219 // TODO(rfindley): this differs from types2 due to the use of Pos() below,
220 // which should actually be on the ~. Confirm that this position is correct.
221 addEmbedded(tlist[0].Pos(), parseUnion(check, tlist))
224 // All methods and embedded elements for this interface are collected;
225 // i.e., this interface may be used in a type set computation.
228 if len(ityp.methods) == 0 && len(ityp.embeddeds) == 0 {
230 ityp.tset = &topTypeSet
234 // sort for API stability
235 sortMethods(ityp.methods)
236 // (don't sort embeddeds: they must correspond to *embedPos entries)
238 // Compute type set with a non-nil *Checker as soon as possible
239 // to report any errors. Subsequent uses of type sets will use
240 // this computed type set and won't need to pass in a *Checker.
242 // Pin the checker to the interface type in the interim, in case the type set
243 // must be used before delayed funcs are processed (see issue #48234).
244 // TODO(rfindley): clean up use of *Checker with computeInterfaceTypeSet
247 computeInterfaceTypeSet(check, iface.Pos(), ityp)
252 func flattenUnion(list []ast.Expr, x ast.Expr) []ast.Expr {
253 if o, _ := x.(*ast.BinaryExpr); o != nil && o.Op == token.OR {
254 list = flattenUnion(list, o.X)
257 return append(list, x)