]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/signature.go
go/types, types2: better error message for some invalid receiver errors (cleanup)
[gostls13.git] / src / cmd / compile / internal / types2 / signature.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 types2
6
7 import "cmd/compile/internal/syntax"
8
9 // ----------------------------------------------------------------------------
10 // API
11
12 // A Signature represents a (non-builtin) function or method type.
13 // The receiver is ignored when comparing signatures for identity.
14 type Signature struct {
15         // We need to keep the scope in Signature (rather than passing it around
16         // and store it in the Func Object) because when type-checking a function
17         // literal we call the general type checker which returns a general Type.
18         // We then unpack the *Signature and use the scope for the literal body.
19         rparams  *TypeParamList // receiver type parameters from left to right, or nil
20         tparams  *TypeParamList // type parameters from left to right, or nil
21         scope    *Scope         // function scope for package-local and non-instantiated signatures; nil otherwise
22         recv     *Var           // nil if not a method
23         params   *Tuple         // (incoming) parameters from left to right; or nil
24         results  *Tuple         // (outgoing) results from left to right; or nil
25         variadic bool           // true if the last parameter's type is of the form ...T (or string, for append built-in only)
26 }
27
28 // NewSignatureType creates a new function type for the given receiver,
29 // receiver type parameters, type parameters, parameters, and results. If
30 // variadic is set, params must hold at least one parameter and the last
31 // parameter must be of unnamed slice type. If recv is non-nil, typeParams must
32 // be empty. If recvTypeParams is non-empty, recv must be non-nil.
33 func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature {
34         if variadic {
35                 n := params.Len()
36                 if n == 0 {
37                         panic("variadic function must have at least one parameter")
38                 }
39                 if _, ok := params.At(n - 1).typ.(*Slice); !ok {
40                         panic("variadic parameter must be of unnamed slice type")
41                 }
42         }
43         sig := &Signature{recv: recv, params: params, results: results, variadic: variadic}
44         if len(recvTypeParams) != 0 {
45                 if recv == nil {
46                         panic("function with receiver type parameters must have a receiver")
47                 }
48                 sig.rparams = bindTParams(recvTypeParams)
49         }
50         if len(typeParams) != 0 {
51                 if recv != nil {
52                         panic("function with type parameters cannot have a receiver")
53                 }
54                 sig.tparams = bindTParams(typeParams)
55         }
56         return sig
57 }
58
59 // Recv returns the receiver of signature s (if a method), or nil if a
60 // function. It is ignored when comparing signatures for identity.
61 //
62 // For an abstract method, Recv returns the enclosing interface either
63 // as a *Named or an *Interface. Due to embedding, an interface may
64 // contain methods whose receiver type is a different interface.
65 func (s *Signature) Recv() *Var { return s.recv }
66
67 // TypeParams returns the type parameters of signature s, or nil.
68 func (s *Signature) TypeParams() *TypeParamList { return s.tparams }
69
70 // SetTypeParams sets the type parameters of signature s.
71 func (s *Signature) SetTypeParams(tparams []*TypeParam) { s.tparams = bindTParams(tparams) }
72
73 // RecvTypeParams returns the receiver type parameters of signature s, or nil.
74 func (s *Signature) RecvTypeParams() *TypeParamList { return s.rparams }
75
76 // Params returns the parameters of signature s, or nil.
77 func (s *Signature) Params() *Tuple { return s.params }
78
79 // Results returns the results of signature s, or nil.
80 func (s *Signature) Results() *Tuple { return s.results }
81
82 // Variadic reports whether the signature s is variadic.
83 func (s *Signature) Variadic() bool { return s.variadic }
84
85 func (s *Signature) Underlying() Type { return s }
86 func (s *Signature) String() string   { return TypeString(s, nil) }
87
88 // ----------------------------------------------------------------------------
89 // Implementation
90
91 // funcType type-checks a function or method type.
92 func (check *Checker) funcType(sig *Signature, recvPar *syntax.Field, tparams []*syntax.Field, ftyp *syntax.FuncType) {
93         check.openScope(ftyp, "function")
94         check.scope.isFunc = true
95         check.recordScope(ftyp, check.scope)
96         sig.scope = check.scope
97         defer check.closeScope()
98
99         if recvPar != nil {
100                 // collect generic receiver type parameters, if any
101                 // - a receiver type parameter is like any other type parameter, except that it is declared implicitly
102                 // - the receiver specification acts as local declaration for its type parameters, which may be blank
103                 _, rname, rparams := check.unpackRecv(recvPar.Type, true)
104                 if len(rparams) > 0 {
105                         tparams := make([]*TypeParam, len(rparams))
106                         for i, rparam := range rparams {
107                                 tparams[i] = check.declareTypeParam(rparam)
108                         }
109                         sig.rparams = bindTParams(tparams)
110                         // Blank identifiers don't get declared, so naive type-checking of the
111                         // receiver type expression would fail in Checker.collectParams below,
112                         // when Checker.ident cannot resolve the _ to a type.
113                         //
114                         // Checker.recvTParamMap maps these blank identifiers to their type parameter
115                         // types, so that they may be resolved in Checker.ident when they fail
116                         // lookup in the scope.
117                         for i, p := range rparams {
118                                 if p.Value == "_" {
119                                         if check.recvTParamMap == nil {
120                                                 check.recvTParamMap = make(map[*syntax.Name]*TypeParam)
121                                         }
122                                         check.recvTParamMap[p] = tparams[i]
123                                 }
124                         }
125                         // determine receiver type to get its type parameters
126                         // and the respective type parameter bounds
127                         var recvTParams []*TypeParam
128                         if rname != nil {
129                                 // recv should be a Named type (otherwise an error is reported elsewhere)
130                                 // Also: Don't report an error via genericType since it will be reported
131                                 //       again when we type-check the signature.
132                                 // TODO(gri) maybe the receiver should be marked as invalid instead?
133                                 if recv, _ := check.genericType(rname, false).(*Named); recv != nil {
134                                         recvTParams = recv.TypeParams().list()
135                                 }
136                         }
137                         // provide type parameter bounds
138                         if len(tparams) == len(recvTParams) {
139                                 smap := makeRenameMap(recvTParams, tparams)
140                                 for i, tpar := range tparams {
141                                         recvTPar := recvTParams[i]
142                                         check.mono.recordCanon(tpar, recvTPar)
143                                         // recvTPar.bound is (possibly) parameterized in the context of the
144                                         // receiver type declaration. Substitute parameters for the current
145                                         // context.
146                                         tpar.bound = check.subst(tpar.obj.pos, recvTPar.bound, smap, nil)
147                                 }
148                         } else if len(tparams) < len(recvTParams) {
149                                 // Reporting an error here is a stop-gap measure to avoid crashes in the
150                                 // compiler when a type parameter/argument cannot be inferred later. It
151                                 // may lead to follow-on errors (see issues #51339, #51343).
152                                 // TODO(gri) find a better solution
153                                 got := measure(len(tparams), "type parameter")
154                                 check.errorf(recvPar, "got %s, but receiver base type declares %d", got, len(recvTParams))
155                         }
156                 }
157         }
158
159         if tparams != nil {
160                 // The parser will complain about invalid type parameters for methods.
161                 check.collectTypeParams(&sig.tparams, tparams)
162         }
163
164         // Value (non-type) parameters' scope starts in the function body. Use a temporary scope for their
165         // declarations and then squash that scope into the parent scope (and report any redeclarations at
166         // that time).
167         scope := NewScope(check.scope, nopos, nopos, "function body (temp. scope)")
168         var recvList []*Var // TODO(gri) remove the need for making a list here
169         if recvPar != nil {
170                 recvList, _ = check.collectParams(scope, []*syntax.Field{recvPar}, false) // use rewritten receiver type, if any
171         }
172         params, variadic := check.collectParams(scope, ftyp.ParamList, true)
173         results, _ := check.collectParams(scope, ftyp.ResultList, false)
174         scope.Squash(func(obj, alt Object) {
175                 var err error_
176                 err.errorf(obj, "%s redeclared in this block", obj.Name())
177                 err.recordAltDecl(alt)
178                 check.report(&err)
179         })
180
181         if recvPar != nil {
182                 // recv parameter list present (may be empty)
183                 // spec: "The receiver is specified via an extra parameter section preceding the
184                 // method name. That parameter section must declare a single parameter, the receiver."
185                 var recv *Var
186                 switch len(recvList) {
187                 case 0:
188                         // error reported by resolver
189                         recv = NewParam(nopos, nil, "", Typ[Invalid]) // ignore recv below
190                 default:
191                         // more than one receiver
192                         check.error(recvList[len(recvList)-1].Pos(), "method must have exactly one receiver")
193                         fallthrough // continue with first receiver
194                 case 1:
195                         recv = recvList[0]
196                 }
197                 sig.recv = recv
198
199                 // Delay validation of receiver type as it may cause premature expansion
200                 // of types the receiver type is dependent on (see issues #51232, #51233).
201                 check.later(func() {
202                         // spec: "The receiver type must be of the form T or *T where T is a type name."
203                         rtyp, _ := deref(recv.typ)
204                         if rtyp == Typ[Invalid] {
205                                 return // error was reported before
206                         }
207                         // spec: "The type denoted by T is called the receiver base type; it must not
208                         // be a pointer or interface type and it must be declared in the same package
209                         // as the method."
210                         switch T := rtyp.(type) {
211                         case *Named:
212                                 T.resolve(check.bestContext(nil))
213                                 // The receiver type may be an instantiated type referred to
214                                 // by an alias (which cannot have receiver parameters for now).
215                                 if T.TypeArgs() != nil && sig.RecvTypeParams() == nil {
216                                         check.errorf(recv, "cannot define new methods on instantiated type %s", rtyp)
217                                         break
218                                 }
219                                 if T.obj.pkg != check.pkg {
220                                         check.errorf(recv, "cannot define new methods on non-local type %s", rtyp)
221                                         break
222                                 }
223                                 var cause string
224                                 switch u := T.under().(type) {
225                                 case *Basic:
226                                         // unsafe.Pointer is treated like a regular pointer
227                                         if u.kind == UnsafePointer {
228                                                 cause = "unsafe.Pointer"
229                                         }
230                                 case *Pointer, *Interface:
231                                         cause = "pointer or interface type"
232                                 case *TypeParam:
233                                         // The underlying type of a receiver base type cannot be a
234                                         // type parameter: "type T[P any] P" is not a valid declaration.
235                                         unreachable()
236                                 }
237                                 if cause != "" {
238                                         check.errorf(recv, "invalid receiver type %s (%s)", rtyp, cause)
239                                 }
240                         case *Basic:
241                                 check.errorf(recv, "cannot define new methods on non-local type %s", rtyp)
242                         default:
243                                 check.errorf(recv, "invalid receiver type %s", recv.typ)
244                         }
245                 }).describef(recv, "validate receiver %s", recv)
246         }
247
248         sig.params = NewTuple(params...)
249         sig.results = NewTuple(results...)
250         sig.variadic = variadic
251 }
252
253 // collectParams declares the parameters of list in scope and returns the corresponding
254 // variable list.
255 func (check *Checker) collectParams(scope *Scope, list []*syntax.Field, variadicOk bool) (params []*Var, variadic bool) {
256         if list == nil {
257                 return
258         }
259
260         var named, anonymous bool
261
262         var typ Type
263         var prev syntax.Expr
264         for i, field := range list {
265                 ftype := field.Type
266                 // type-check type of grouped fields only once
267                 if ftype != prev {
268                         prev = ftype
269                         if t, _ := ftype.(*syntax.DotsType); t != nil {
270                                 ftype = t.Elem
271                                 if variadicOk && i == len(list)-1 {
272                                         variadic = true
273                                 } else {
274                                         check.softErrorf(t, "can only use ... with final parameter in list")
275                                         // ignore ... and continue
276                                 }
277                         }
278                         typ = check.varType(ftype)
279                 }
280                 // The parser ensures that f.Tag is nil and we don't
281                 // care if a constructed AST contains a non-nil tag.
282                 if field.Name != nil {
283                         // named parameter
284                         name := field.Name.Value
285                         if name == "" {
286                                 check.error(field.Name, invalidAST+"anonymous parameter")
287                                 // ok to continue
288                         }
289                         par := NewParam(field.Name.Pos(), check.pkg, name, typ)
290                         check.declare(scope, field.Name, par, scope.pos)
291                         params = append(params, par)
292                         named = true
293                 } else {
294                         // anonymous parameter
295                         par := NewParam(field.Pos(), check.pkg, "", typ)
296                         check.recordImplicit(field, par)
297                         params = append(params, par)
298                         anonymous = true
299                 }
300         }
301
302         if named && anonymous {
303                 check.error(list[0], invalidAST+"list contains both named and anonymous parameters")
304                 // ok to continue
305         }
306
307         // For a variadic function, change the last parameter's type from T to []T.
308         // Since we type-checked T rather than ...T, we also need to retro-actively
309         // record the type for ...T.
310         if variadic {
311                 last := params[len(params)-1]
312                 last.typ = &Slice{elem: last.typ}
313                 check.recordTypeAndValue(list[len(list)-1].Type, typexpr, last.typ, nil)
314         }
315
316         return
317 }