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