]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/interface.go
[dev.cmdgo] all: merge master (c2f96e6) into dev.cmdgo
[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
47 // types. NewInterfaceType takes ownership of the provided methods and may
48 // modify their types by setting missing receivers.
49 //
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
55         }
56
57         // set method receivers if necessary
58         typ := new(Interface)
59         for _, m := range methods {
60                 if sig := m.typ.(*Signature); sig.recv == nil {
61                         sig.recv = NewVar(m.pos, m.pkg, "", typ)
62                 }
63         }
64
65         // sort for API stability
66         sortMethods(methods)
67
68         typ.methods = methods
69         typ.embeddeds = embeddeds
70         typ.complete = true
71
72         return typ
73 }
74
75 // NumExplicitMethods returns the number of explicitly declared methods of interface t.
76 func (t *Interface) NumExplicitMethods() int { return len(t.methods) }
77
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] }
81
82 // NumEmbeddeds returns the number of embedded types in interface t.
83 func (t *Interface) NumEmbeddeds() int { return len(t.embeddeds) }
84
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.
87 //
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 }
90
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] }
93
94 // NumMethods returns the total number of methods of interface t.
95 func (t *Interface) NumMethods() int { return t.typeSet().NumMethods() }
96
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) }
100
101 // Empty reports whether t is the empty interface.
102 func (t *Interface) Empty() bool { return t.typeSet().IsAll() }
103
104 // IsComparable reports whether each type in interface t's type set is comparable.
105 func (t *Interface) IsComparable() bool { return t.typeSet().IsComparable() }
106
107 // IsConstraint reports whether interface t is not just a method set.
108 func (t *Interface) IsConstraint() bool { return !t.typeSet().IsMethodSet() }
109
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.
115 //
116 // Interface types that have been completed are safe for concurrent use.
117 func (t *Interface) Complete() *Interface {
118         if !t.complete {
119                 t.complete = true
120         }
121         t.typeSet() // checks if t.tset is already set
122         return t
123 }
124
125 func (t *Interface) Underlying() Type { return t }
126 func (t *Interface) String() string   { return TypeString(t, nil) }
127
128 // ----------------------------------------------------------------------------
129 // Implementation
130
131 func (check *Checker) interfaceType(ityp *Interface, iface *ast.InterfaceType, def *Named) {
132         var tlist []ast.Expr
133         var tname *ast.Ident // "type" name of first entry in a type list declaration
134
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)
139                 }
140                 *ityp.embedPos = append(*ityp.embedPos, pos)
141         }
142
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)))
147                         continue
148                 }
149
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.)
154                 name := f.Names[0]
155                 if name.Name == "_" {
156                         check.errorf(name, _BlankIfaceMethod, "invalid method name _")
157                         continue // ignore
158                 }
159
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")
166                         }
167                         // For now, collect all type list entries as if it
168                         // were a single union, where each union element is
169                         // of the form ~T.
170                         // TODO(rfindley) remove once we disallow type lists
171                         op := new(ast.UnaryExpr)
172                         op.Op = token.TILDE
173                         op.X = f.Type
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")
179                         }
180                         tname = name
181                         continue
182                 }
183
184                 typ := check.typ(f.Type)
185                 sig, _ := typ.(*Signature)
186                 if sig == nil {
187                         if typ != Typ[Invalid] {
188                                 check.invalidAST(f.Type, "%s is not a method signature", typ)
189                         }
190                         continue // ignore
191                 }
192
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 {
199                                 at = tparams
200                         }
201                         check.errorf(at, _Todo, "methods cannot have type parameters")
202                 }
203
204                 // use named receiver type if available (for better error messages)
205                 var recvTyp Type = ityp
206                 if def != nil {
207                         recvTyp = def
208                 }
209                 sig.recv = NewVar(name.Pos(), check.pkg, "", recvTyp)
210
211                 m := NewFunc(name.Pos(), check.pkg, name.Name, sig)
212                 check.recordDef(name, m)
213                 ityp.methods = append(ityp.methods, m)
214         }
215
216         // type constraints
217         if tlist != nil {
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))
221         }
222
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.
225         ityp.complete = true
226
227         if len(ityp.methods) == 0 && len(ityp.embeddeds) == 0 {
228                 // empty interface
229                 ityp.tset = &topTypeSet
230                 return
231         }
232
233         // sort for API stability
234         sortMethods(ityp.methods)
235         // (don't sort embeddeds: they must correspond to *embedPos entries)
236
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) })
241 }
242
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)
246                 x = o.Y
247         }
248         return append(list, x)
249 }