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.
9 "go/internal/typeparams"
13 // ----------------------------------------------------------------------------
16 // An Interface represents an interface type.
17 type Interface struct {
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(nil, 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 // IsConstraint reports whether interface t is not just a method set.
108 func (t *Interface) IsConstraint() bool { return !t.typeSet().IsMethodSet() }
110 // Complete computes the interface's type set. It must be called by users of
111 // NewInterfaceType and NewInterface after the interface's embedded types are
112 // fully defined and before using the interface type in any way other than to
113 // form other types. The interface must not contain duplicate methods or a
114 // panic occurs. Complete returns the receiver.
116 // Interface types that have been completed are safe for concurrent use.
117 func (t *Interface) Complete() *Interface {
121 t.typeSet() // checks if t.tset is already set
125 func (t *Interface) Underlying() Type { return t }
126 func (t *Interface) String() string { return TypeString(t, nil) }
128 // ----------------------------------------------------------------------------
131 func (check *Checker) interfaceType(ityp *Interface, iface *ast.InterfaceType, def *Named) {
133 var tname *ast.Ident // "type" name of first entry in a type list declaration
135 addEmbedded := func(pos token.Pos, typ Type) {
136 ityp.embeddeds = append(ityp.embeddeds, typ)
137 if ityp.embedPos == nil {
138 ityp.embedPos = new([]token.Pos)
140 *ityp.embedPos = append(*ityp.embedPos, pos)
143 for _, f := range iface.Methods.List {
144 if len(f.Names) == 0 {
145 // We have an embedded type; possibly a union of types.
146 addEmbedded(f.Type.Pos(), parseUnion(check, flattenUnion(nil, f.Type)))
150 // We have a method with name f.Names[0], or a type
151 // of a type list (name.Name == "type").
152 // (The parser ensures that there's only one method
153 // and we don't care if a constructed AST has more.)
155 if name.Name == "_" {
156 check.errorf(name, _BlankIfaceMethod, "invalid method name _")
160 // TODO(rfindley) Remove type list handling once the parser doesn't accept type lists anymore.
161 if name.Name == "type" {
162 // Report an error for the first type list per interface
163 // if we don't allow type lists, but continue.
164 if !allowTypeLists && tlist == nil {
165 check.softErrorf(name, _Todo, "use generalized embedding syntax instead of a type list")
167 // For now, collect all type list entries as if it
168 // were a single union, where each union element is
170 // TODO(rfindley) remove once we disallow type lists
171 op := new(ast.UnaryExpr)
174 tlist = append(tlist, op)
175 // Report an error if we have multiple type lists in an
176 // interface, but only if they are permitted in the first place.
177 if allowTypeLists && tname != nil && tname != name {
178 check.errorf(name, _Todo, "cannot have multiple type lists in an interface")
184 typ := check.typ(f.Type)
185 sig, _ := typ.(*Signature)
187 if typ != Typ[Invalid] {
188 check.invalidAST(f.Type, "%s is not a method signature", typ)
193 // Always type-check method type parameters but complain if they are not enabled.
194 // (This extra check is needed here because interface method signatures don't have
195 // a receiver specification.)
196 if sig.tparams != nil {
197 var at positioner = f.Type
198 if tparams := typeparams.Get(f.Type); tparams != nil {
201 check.errorf(at, _Todo, "methods cannot have type parameters")
204 // use named receiver type if available (for better error messages)
205 var recvTyp Type = ityp
209 sig.recv = NewVar(name.Pos(), check.pkg, "", recvTyp)
211 m := NewFunc(name.Pos(), check.pkg, name.Name, sig)
212 check.recordDef(name, m)
213 ityp.methods = append(ityp.methods, m)
218 // TODO(rfindley): this differs from types2 due to the use of Pos() below,
219 // which should actually be on the ~. Confirm that this position is correct.
220 addEmbedded(tlist[0].Pos(), parseUnion(check, tlist))
223 // All methods and embedded elements for this interface are collected;
224 // i.e., this interface is may be used in a type set computation.
227 if len(ityp.methods) == 0 && len(ityp.embeddeds) == 0 {
229 ityp.tset = &topTypeSet
233 // sort for API stability
234 sortMethods(ityp.methods)
235 // (don't sort embeddeds: they must correspond to *embedPos entries)
237 // Compute type set with a non-nil *Checker as soon as possible
238 // to report any errors. Subsequent uses of type sets will use
239 // this computed type set and won't need to pass in a *Checker.
240 check.later(func() { computeInterfaceTypeSet(check, iface.Pos(), ityp) })
243 func flattenUnion(list []ast.Expr, x ast.Expr) []ast.Expr {
244 if o, _ := x.(*ast.BinaryExpr); o != nil && o.Op == token.OR {
245 list = flattenUnion(list, o.X)
248 return append(list, x)