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 computeTypeSet(nil, token.NoPos, t) }
30 // is reports whether interface t represents types that all satisfy f.
31 func (t *Interface) is(f func(Type, bool) bool) bool {
32 switch t := t.typeSet().types.(type) {
34 // TODO(gri) should settle on top or nil to represent this case
35 return false // we must have at least one type! (was bug)
37 return t.is(func(t *term) bool { return f(t.typ, t.tilde) })
43 // emptyInterface represents the empty (completed) interface
44 var emptyInterface = Interface{complete: true, tset: &topTypeSet}
46 // NewInterface returns a new interface for the given methods and embedded types.
47 // NewInterface takes ownership of the provided methods and may modify their types
48 // by setting missing receivers.
50 // Deprecated: Use NewInterfaceType instead which allows arbitrary embedded types.
51 func NewInterface(methods []*Func, embeddeds []*Named) *Interface {
52 tnames := make([]Type, len(embeddeds))
53 for i, t := range embeddeds {
56 return NewInterfaceType(methods, tnames)
59 // NewInterfaceType returns a new interface for the given methods and embedded types.
60 // NewInterfaceType takes ownership of the provided methods and may modify their types
61 // by setting missing receivers.
62 func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface {
63 if len(methods) == 0 && len(embeddeds) == 0 {
64 return &emptyInterface
67 // set method receivers if necessary
69 for _, m := range methods {
70 if sig := m.typ.(*Signature); sig.recv == nil {
71 sig.recv = NewVar(m.pos, m.pkg, "", typ)
75 // sort for API stability
79 typ.embeddeds = embeddeds
85 // NumExplicitMethods returns the number of explicitly declared methods of interface t.
86 func (t *Interface) NumExplicitMethods() int { return len(t.methods) }
88 // ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods().
89 // The methods are ordered by their unique Id.
90 func (t *Interface) ExplicitMethod(i int) *Func { return t.methods[i] }
92 // NumEmbeddeds returns the number of embedded types in interface t.
93 func (t *Interface) NumEmbeddeds() int { return len(t.embeddeds) }
95 // Embedded returns the i'th embedded defined (*Named) type of interface t for 0 <= i < t.NumEmbeddeds().
96 // The result is nil if the i'th embedded type is not a defined type.
98 // Deprecated: Use EmbeddedType which is not restricted to defined (*Named) types.
99 func (t *Interface) Embedded(i int) *Named { tname, _ := t.embeddeds[i].(*Named); return tname }
101 // EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().
102 func (t *Interface) EmbeddedType(i int) Type { return t.embeddeds[i] }
104 // NumMethods returns the total number of methods of interface t.
105 func (t *Interface) NumMethods() int { return t.typeSet().NumMethods() }
107 // Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
108 // The methods are ordered by their unique Id.
109 func (t *Interface) Method(i int) *Func { return t.typeSet().Method(i) }
111 // Empty reports whether t is the empty interface.
112 func (t *Interface) Empty() bool { return t.typeSet().IsTop() }
114 // IsComparable reports whether each type in interface t's type set is comparable.
115 func (t *Interface) IsComparable() bool { return t.typeSet().IsComparable() }
117 // IsConstraint reports whether interface t is not just a method set.
118 func (t *Interface) IsConstraint() bool { return !t.typeSet().IsMethodSet() }
120 // isSatisfiedBy reports whether interface t's type list is satisfied by the type typ.
121 // If the type list is empty (absent), typ trivially satisfies the interface.
122 // TODO(gri) This is not a great name. Eventually, we should have a more comprehensive
123 // "implements" predicate.
124 func (t *Interface) isSatisfiedBy(typ Type) bool {
126 switch t := t.typeSet().types.(type) {
128 return true // no type restrictions
130 r, _ := t.intersect(typ, false)
133 return Identical(t, typ)
137 // Complete computes the interface's type set. It must be called by users of
138 // NewInterfaceType and NewInterface after the interface's embedded types are
139 // fully defined and before using the interface type in any way other than to
140 // form other types. The interface must not contain duplicate methods or a
141 // panic occurs. Complete returns the receiver.
143 // Deprecated: Type sets are now computed lazily, on demand; this function
144 // is only here for backward-compatibility. It does not have to
145 // be called explicitly anymore.
146 func (t *Interface) Complete() *Interface {
147 // Some tests are still depending on the state change
148 // (string representation of an Interface not containing an
149 // /* incomplete */ marker) caused by the explicit Complete
150 // call, so we compute the type set eagerly here.
156 func (t *Interface) Underlying() Type { return t }
157 func (t *Interface) String() string { return TypeString(t, nil) }
159 // ----------------------------------------------------------------------------
162 func (check *Checker) interfaceType(ityp *Interface, iface *ast.InterfaceType, def *Named) {
164 var tname *ast.Ident // "type" name of first entry in a type list declaration
166 addEmbedded := func(pos token.Pos, typ Type) {
167 ityp.embeddeds = append(ityp.embeddeds, typ)
168 if ityp.embedPos == nil {
169 ityp.embedPos = new([]token.Pos)
171 *ityp.embedPos = append(*ityp.embedPos, pos)
174 for _, f := range iface.Methods.List {
175 if len(f.Names) == 0 {
176 // We have an embedded type; possibly a union of types.
177 addEmbedded(f.Type.Pos(), parseUnion(check, flattenUnion(nil, f.Type)))
181 // We have a method with name f.Names[0], or a type
182 // of a type list (name.Name == "type").
183 // (The parser ensures that there's only one method
184 // and we don't care if a constructed AST has more.)
186 if name.Name == "_" {
187 check.errorf(name, _BlankIfaceMethod, "invalid method name _")
191 // TODO(rfindley) Remove type list handling once the parser doesn't accept type lists anymore.
192 if name.Name == "type" {
193 // Report an error for the first type list per interface
194 // if we don't allow type lists, but continue.
195 if !allowTypeLists && tlist == nil {
196 check.softErrorf(name, _Todo, "use generalized embedding syntax instead of a type list")
198 // For now, collect all type list entries as if it
199 // were a single union, where each union element is
201 // TODO(rfindley) remove once we disallow type lists
202 op := new(ast.UnaryExpr)
205 tlist = append(tlist, op)
206 // Report an error if we have multiple type lists in an
207 // interface, but only if they are permitted in the first place.
208 if allowTypeLists && tname != nil && tname != name {
209 check.errorf(name, _Todo, "cannot have multiple type lists in an interface")
215 typ := check.typ(f.Type)
216 sig, _ := typ.(*Signature)
218 if typ != Typ[Invalid] {
219 check.invalidAST(f.Type, "%s is not a method signature", typ)
224 // Always type-check method type parameters but complain if they are not enabled.
225 // (This extra check is needed here because interface method signatures don't have
226 // a receiver specification.)
227 if sig.tparams != nil {
228 var at positioner = f.Type
229 if tparams := typeparams.Get(f.Type); tparams != nil {
232 check.errorf(at, _Todo, "methods cannot have type parameters")
235 // use named receiver type if available (for better error messages)
236 var recvTyp Type = ityp
240 sig.recv = NewVar(name.Pos(), check.pkg, "", recvTyp)
242 m := NewFunc(name.Pos(), check.pkg, name.Name, sig)
243 check.recordDef(name, m)
244 ityp.methods = append(ityp.methods, m)
249 // TODO(rfindley): this differs from types2 due to the use of Pos() below,
250 // which should actually be on the ~. Confirm that this position is correct.
251 addEmbedded(tlist[0].Pos(), parseUnion(check, tlist))
254 // All methods and embedded elements for this interface are collected;
255 // i.e., this interface is may be used in a type set computation.
258 if len(ityp.methods) == 0 && len(ityp.embeddeds) == 0 {
260 ityp.tset = &topTypeSet
264 // sort for API stability
265 sortMethods(ityp.methods)
266 // (don't sort embeddeds: they must correspond to *embedPos entries)
268 // Compute type set with a non-nil *Checker as soon as possible
269 // to report any errors. Subsequent uses of type sets will use
270 // this computed type set and won't need to pass in a *Checker.
271 check.later(func() { computeTypeSet(check, iface.Pos(), ityp) })
274 func flattenUnion(list []ast.Expr, x ast.Expr) []ast.Expr {
275 if o, _ := x.(*ast.BinaryExpr); o != nil && o.Op == token.OR {
276 list = flattenUnion(list, o.X)
279 return append(list, x)