]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/interface.go
go/types: better names for things (cleanup)
[gostls13.git] / src / go / types / interface.go
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.
4
5 package types
6
7 import (
8         "go/ast"
9         "go/internal/typeparams"
10         "go/token"
11 )
12
13 // ----------------------------------------------------------------------------
14 // API
15
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
23
24         tset *_TypeSet // type set described by this interface, computed lazily
25 }
26
27 // typeSet returns the type set for interface t.
28 func (t *Interface) typeSet() *_TypeSet { return computeInterfaceTypeSet(nil, token.NoPos, t) }
29
30 // emptyInterface represents the empty (completed) interface
31 var emptyInterface = Interface{complete: true, tset: &topTypeSet}
32
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.
36 //
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 {
41                 tnames[i] = t
42         }
43         return NewInterfaceType(methods, tnames)
44 }
45
46 // NewInterfaceType returns a new interface for the given methods and embedded types.
47 // NewInterfaceType takes ownership of the provided methods and may modify their types
48 // by setting missing receivers.
49 func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface {
50         if len(methods) == 0 && len(embeddeds) == 0 {
51                 return &emptyInterface
52         }
53
54         // set method receivers if necessary
55         typ := new(Interface)
56         for _, m := range methods {
57                 if sig := m.typ.(*Signature); sig.recv == nil {
58                         sig.recv = NewVar(m.pos, m.pkg, "", typ)
59                 }
60         }
61
62         // sort for API stability
63         sortMethods(methods)
64
65         typ.methods = methods
66         typ.embeddeds = embeddeds
67         typ.complete = true
68
69         return typ
70 }
71
72 // NumExplicitMethods returns the number of explicitly declared methods of interface t.
73 func (t *Interface) NumExplicitMethods() int { return len(t.methods) }
74
75 // ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods().
76 // The methods are ordered by their unique Id.
77 func (t *Interface) ExplicitMethod(i int) *Func { return t.methods[i] }
78
79 // NumEmbeddeds returns the number of embedded types in interface t.
80 func (t *Interface) NumEmbeddeds() int { return len(t.embeddeds) }
81
82 // Embedded returns the i'th embedded defined (*Named) type of interface t for 0 <= i < t.NumEmbeddeds().
83 // The result is nil if the i'th embedded type is not a defined type.
84 //
85 // Deprecated: Use EmbeddedType which is not restricted to defined (*Named) types.
86 func (t *Interface) Embedded(i int) *Named { tname, _ := t.embeddeds[i].(*Named); return tname }
87
88 // EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().
89 func (t *Interface) EmbeddedType(i int) Type { return t.embeddeds[i] }
90
91 // NumMethods returns the total number of methods of interface t.
92 func (t *Interface) NumMethods() int { return t.typeSet().NumMethods() }
93
94 // Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
95 // The methods are ordered by their unique Id.
96 func (t *Interface) Method(i int) *Func { return t.typeSet().Method(i) }
97
98 // Empty reports whether t is the empty interface.
99 func (t *Interface) Empty() bool { return t.typeSet().IsAll() }
100
101 // IsComparable reports whether each type in interface t's type set is comparable.
102 func (t *Interface) IsComparable() bool { return t.typeSet().IsComparable() }
103
104 // IsConstraint reports whether interface t is not just a method set.
105 func (t *Interface) IsConstraint() bool { return !t.typeSet().IsMethodSet() }
106
107 // Complete computes the interface's type set. It must be called by users of
108 // NewInterfaceType and NewInterface after the interface's embedded types are
109 // fully defined and before using the interface type in any way other than to
110 // form other types. The interface must not contain duplicate methods or a
111 // panic occurs. Complete returns the receiver.
112 //
113 // Deprecated: Type sets are now computed lazily, on demand; this function
114 //             is only here for backward-compatibility. It does not have to
115 //             be called explicitly anymore.
116 func (t *Interface) Complete() *Interface {
117         // Some tests are still depending on the state change
118         // (string representation of an Interface not containing an
119         // /* incomplete */ marker) caused by the explicit Complete
120         // call, so we compute the type set eagerly here.
121         t.complete = true
122         t.typeSet()
123         return t
124 }
125
126 func (t *Interface) Underlying() Type { return t }
127 func (t *Interface) String() string   { return TypeString(t, nil) }
128
129 // ----------------------------------------------------------------------------
130 // Implementation
131
132 func (check *Checker) interfaceType(ityp *Interface, iface *ast.InterfaceType, def *Named) {
133         var tlist []ast.Expr
134         var tname *ast.Ident // "type" name of first entry in a type list declaration
135
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)
140                 }
141                 *ityp.embedPos = append(*ityp.embedPos, pos)
142         }
143
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)))
148                         continue
149                 }
150
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.)
155                 name := f.Names[0]
156                 if name.Name == "_" {
157                         check.errorf(name, _BlankIfaceMethod, "invalid method name _")
158                         continue // ignore
159                 }
160
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")
167                         }
168                         // For now, collect all type list entries as if it
169                         // were a single union, where each union element is
170                         // of the form ~T.
171                         // TODO(rfindley) remove once we disallow type lists
172                         op := new(ast.UnaryExpr)
173                         op.Op = token.TILDE
174                         op.X = f.Type
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")
180                         }
181                         tname = name
182                         continue
183                 }
184
185                 typ := check.typ(f.Type)
186                 sig, _ := typ.(*Signature)
187                 if sig == nil {
188                         if typ != Typ[Invalid] {
189                                 check.invalidAST(f.Type, "%s is not a method signature", typ)
190                         }
191                         continue // ignore
192                 }
193
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 tparams := typeparams.Get(f.Type); tparams != nil {
200                                 at = tparams
201                         }
202                         check.errorf(at, _Todo, "methods cannot have type parameters")
203                 }
204
205                 // use named receiver type if available (for better error messages)
206                 var recvTyp Type = ityp
207                 if def != nil {
208                         recvTyp = def
209                 }
210                 sig.recv = NewVar(name.Pos(), check.pkg, "", recvTyp)
211
212                 m := NewFunc(name.Pos(), check.pkg, name.Name, sig)
213                 check.recordDef(name, m)
214                 ityp.methods = append(ityp.methods, m)
215         }
216
217         // type constraints
218         if tlist != nil {
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))
222         }
223
224         // All methods and embedded elements for this interface are collected;
225         // i.e., this interface is may be used in a type set computation.
226         ityp.complete = true
227
228         if len(ityp.methods) == 0 && len(ityp.embeddeds) == 0 {
229                 // empty interface
230                 ityp.tset = &topTypeSet
231                 return
232         }
233
234         // sort for API stability
235         sortMethods(ityp.methods)
236         // (don't sort embeddeds: they must correspond to *embedPos entries)
237
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.
241         check.later(func() { computeInterfaceTypeSet(check, iface.Pos(), ityp) })
242 }
243
244 func flattenUnion(list []ast.Expr, x ast.Expr) []ast.Expr {
245         if o, _ := x.(*ast.BinaryExpr); o != nil && o.Op == token.OR {
246                 list = flattenUnion(list, o.X)
247                 x = o.Y
248         }
249         return append(list, x)
250 }