Debian Codegraph @

src/go/types/signature.go

raw
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 "go/token"
11 . "internal/types/errors"
12 "path/filepath"
13 "strings"
14 )
15
16 // ----------------------------------------------------------------------------
17 // API
18
19 // A Signature represents a (non-builtin) function or method type.
20 // The receiver is ignored when comparing signatures for identity.
21 type Signature struct {
22 // We need to keep the scope in Signature (rather than passing it around
23 // and store it in the Func Object) because when type-checking a function
24 // literal we call the general type checker which returns a general Type.
25 // We then unpack the *Signature and use the scope for the literal body.
26 rparams *TypeParamList // receiver type parameters from left to right, or nil
27 tparams *TypeParamList // type parameters from left to right, or nil
28 scope *Scope // function scope for package-local and non-instantiated signatures; nil otherwise
29 recv *Var // nil if not a method
30 params *Tuple // (incoming) parameters from left to right; or nil
31 results *Tuple // (outgoing) results from left to right; or nil
32 variadic bool // true if the last parameter's type is of the form ...T (or string, for append built-in only)
33 }
34
35 // NewSignature returns a new function type for the given receiver, parameters,
36 // and results, either of which may be nil. If variadic is set, the function
37 // is variadic, it must have at least one parameter, and the last parameter
38 // must be of unnamed slice type.
39 //
40 // Deprecated: Use [NewSignatureType] instead which allows for type parameters.
41 //
42 //go:fix inline
43 func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature {
44 return NewSignatureType(recv, nil, nil, params, results, variadic)
45 }
46
47 // NewSignatureType creates a new function type for the given receiver,
48 // receiver type parameters, type parameters, parameters, and results.
49 // If variadic is set, params must hold at least one parameter and the
50 // last parameter must be an unnamed slice or a type parameter whose
51 // type set has an unnamed slice as common underlying type.
52 // As a special case, for variadic signatures the last parameter may
53 // also be a string type, or a type parameter containing a mix of byte
54 // slices and string types in its type set.
55 // If recv is non-nil, typeParams must be empty. If recvTypeParams is
56 // non-empty, recv must be non-nil.
57 func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature {
58 if variadic {
59 n := params.Len()
60 if n == 0 {
61 panic("variadic function must have at least one parameter")
62 }
63 last := params.At(n - 1).typ
64 var S *Slice
65 typeset(last, func(t, _ Type) bool {
66 if t == nil {
67 return false
68 }
69 var s *Slice
70 if isString(t) {
71 s = NewSlice(universeByte)
72 } else {
73 s, _ = Unalias(t).(*Slice) // don't accept a named slice type
74 }
75 if S == nil {
76 S = s
77 } else if s == nil || !Identical(S, s) {
78 S = nil
79 return false
80 }
81 return true
82 })
83 if S == nil {
84 panic(fmt.Sprintf("got %s, want variadic parameter of unnamed slice or string type", last))
85 }
86 }
87 sig := &Signature{recv: recv, params: params, results: results, variadic: variadic}
88 if len(recvTypeParams) != 0 {
89 if recv == nil {
90 panic("function with receiver type parameters must have a receiver")
91 }
92 sig.rparams = bindTParams(recvTypeParams)
93 }
94 if len(typeParams) != 0 {
95 if recv != nil {
96 panic("function with type parameters cannot have a receiver")
97 }
98 sig.tparams = bindTParams(typeParams)
99 }
100 return sig
101 }
102
103 // Recv returns the receiver of signature s (if a method), or nil if a
104 // function. It is ignored when comparing signatures for identity.
105 //
106 // For an abstract method, Recv returns the enclosing interface either
107 // as a *[Named] or an *[Interface]. Due to embedding, an interface may
108 // contain methods whose receiver type is a different interface.
109 func (s *Signature) Recv() *Var { return s.recv }
110
111 // TypeParams returns the type parameters of signature s, or nil.
112 func (s *Signature) TypeParams() *TypeParamList { return s.tparams }
113
114 // RecvTypeParams returns the receiver type parameters of signature s, or nil.
115 func (s *Signature) RecvTypeParams() *TypeParamList { return s.rparams }
116
117 // Params returns the parameters of signature s, or nil.
118 func (s *Signature) Params() *Tuple { return s.params }
119
120 // Results returns the results of signature s, or nil.
121 func (s *Signature) Results() *Tuple { return s.results }
122
123 // Variadic reports whether the signature s is variadic.
124 func (s *Signature) Variadic() bool { return s.variadic }
125
126 func (s *Signature) Underlying() Type { return s }
127 func (s *Signature) String() string { return TypeString(s, nil) }
128
129 // ----------------------------------------------------------------------------
130 // Implementation
131
132 // funcType type-checks a function or method type.
133 func (check *Checker) funcType(sig *Signature, recvPar *ast.FieldList, ftyp *ast.FuncType) {
134 check.openScope(ftyp, "function")
135 check.scope.isFunc = true
136 check.recordScope(ftyp, check.scope)
137 sig.scope = check.scope
138 defer check.closeScope()
139
140 // collect method receiver, if any
141 var recv *Var
142 var rparams *TypeParamList
143 if recvPar != nil && recvPar.NumFields() > 0 {
144 // We have at least one receiver; make sure we don't have more than one.
145 if n := len(recvPar.List); n > 1 {
146 check.error(recvPar.List[n-1], InvalidRecv, "method has multiple receivers")
147 // continue with first one
148 }
149 // all type parameters' scopes start after the method name
150 scopePos := ftyp.Pos()
151 recv, rparams = check.collectRecv(recvPar.List[0], scopePos)
152 }
153
154 // collect and declare function type parameters
155 if ftyp.TypeParams != nil {
156 // Always type-check method type parameters but complain that they are not allowed.
157 // (A separate check is needed when type-checking interface method signatures because
158 // they don't have a receiver specification.)
159 if recvPar != nil {
160 check.error(ftyp.TypeParams, InvalidMethodTypeParams, "methods cannot have type parameters")
161 }
162 check.collectTypeParams(&sig.tparams, ftyp.TypeParams)
163 }
164
165 // collect ordinary and result parameters
166 pnames, params, variadic := check.collectParams(ParamVar, ftyp.Params)
167 rnames, results, _ := check.collectParams(ResultVar, ftyp.Results)
168
169 // declare named receiver, ordinary, and result parameters
170 scopePos := ftyp.End() // all parameter's scopes start after the signature
171 if recv != nil && recv.name != "" {
172 check.declare(check.scope, recvPar.List[0].Names[0], recv, scopePos)
173 }
174 check.declareParams(pnames, params, scopePos)
175 check.declareParams(rnames, results, scopePos)
176
177 sig.recv = recv
178 sig.rparams = rparams
179 sig.params = NewTuple(params...)
180 sig.results = NewTuple(results...)
181 sig.variadic = variadic
182 }
183
184 // collectRecv extracts the method receiver and its type parameters (if any) from rparam.
185 // It declares the type parameters (but not the receiver) in the current scope, and
186 // returns the receiver variable and its type parameter list (if any).
187 func (check *Checker) collectRecv(rparam *ast.Field, scopePos token.Pos) (*Var, *TypeParamList) {
188 // Unpack the receiver parameter which is of the form
189 //
190 // "(" [rfield] ["*"] rbase ["[" rtparams "]"] ")"
191 //
192 // The receiver name rname, the pointer indirection, and the
193 // receiver type parameters rtparams may not be present.
194 rptr, rbase, rtparams := check.unpackRecv(rparam.Type, true)
195
196 // Determine the receiver base type.
197 var recvType Type = Typ[Invalid]
198 var recvTParamsList *TypeParamList
199 if rtparams == nil {
200 // If there are no type parameters, we can simply typecheck rparam.Type.
201 // If that is a generic type, varType will complain.
202 // Further receiver constraints will be checked later, with validRecv.
203 // We use rparam.Type (rather than base) to correctly record pointer
204 // and parentheses in types.Info (was bug, see go.dev/issue/68639).
205 recvType = check.varType(rparam.Type)
206 // Defining new methods on instantiated (alias or defined) types is not permitted.
207 // Follow literal pointer/alias type chain and check.
208 // (Correct code permits at most one pointer indirection, but for this check it
209 // doesn't matter if we have multiple pointers.)
210 a, _ := unpointer(recvType).(*Alias) // recvType is not generic per above
211 for a != nil {
212 baseType := unpointer(a.fromRHS)
213 if g, _ := baseType.(genericType); g != nil && g.TypeParams() != nil {
214 check.errorf(rbase, InvalidRecv, "cannot define new methods on instantiated type %s", g)
215 recvType = Typ[Invalid] // avoid follow-on errors by Checker.validRecv
216 break
217 }
218 a, _ = baseType.(*Alias)
219 }
220 } else {
221 // If there are type parameters, rbase must denote a generic base type.
222 // Important: rbase must be resolved before declaring any receiver type
223 // parameters (which may have the same name, see below).
224 var baseType *Named // nil if not valid
225 var cause string
226 if t := check.genericType(rbase, &cause); isValid(t) {
227 switch t := t.(type) {
228 case *Named:
229 baseType = t
230 case *Alias:
231 // Methods on generic aliases are not permitted.
232 // Only report an error if the alias type is valid.
233 if isValid(unalias(t)) {
234 check.errorf(rbase, InvalidRecv, "cannot define new methods on generic alias type %s", t)
235 }
236 // Ok to continue but do not set basetype in this case so that
237 // recvType remains invalid (was bug, see go.dev/issue/70417).
238 default:
239 panic("unreachable")
240 }
241 } else {
242 if cause != "" {
243 check.errorf(rbase, InvalidRecv, "%s", cause)
244 }
245 // Ok to continue but do not set baseType (see comment above).
246 }
247
248 // Collect the type parameters declared by the receiver (see also
249 // Checker.collectTypeParams). The scope of the type parameter T in
250 // "func (r T[T]) f() {}" starts after f, not at r, so we declare it
251 // after typechecking rbase (see go.dev/issue/52038).
252 recvTParams := make([]*TypeParam, len(rtparams))
253 for i, rparam := range rtparams {
254 tpar := check.declareTypeParam(rparam, scopePos)
255 recvTParams[i] = tpar
256 // For historic reasons, type parameters in receiver type expressions
257 // are considered both definitions and uses and thus must be recorded
258 // in the Info.Uses and Info.Types maps (see go.dev/issue/68670).
259 check.recordUse(rparam, tpar.obj)
260 check.recordTypeAndValue(rparam, typexpr, tpar, nil)
261 }
262 recvTParamsList = bindTParams(recvTParams)
263
264 // Get the type parameter bounds from the receiver base type
265 // and set them for the respective (local) receiver type parameters.
266 if baseType != nil {
267 baseTParams := baseType.TypeParams().list()
268 if len(recvTParams) == len(baseTParams) {
269 smap := makeRenameMap(baseTParams, recvTParams)
270 for i, recvTPar := range recvTParams {
271 baseTPar := baseTParams[i]
272 check.mono.recordCanon(recvTPar, baseTPar)
273 // baseTPar.bound is possibly parameterized by other type parameters
274 // defined by the generic base type. Substitute those parameters with
275 // the receiver type parameters declared by the current method.
276 recvTPar.bound = check.subst(recvTPar.obj.pos, baseTPar.bound, smap, nil, check.context())
277 }
278 } else {
279 got := measure(len(recvTParams), "type parameter")
280 check.errorf(rbase, BadRecv, "receiver declares %s, but receiver base type declares %d", got, len(baseTParams))
281 }
282
283 // The type parameters declared by the receiver also serve as
284 // type arguments for the receiver type. Instantiate the receiver.
285 check.verifyVersionf(rbase, go1_18, "type instantiation")
286 targs := make([]Type, len(recvTParams))
287 for i, targ := range recvTParams {
288 targs[i] = targ
289 }
290 recvType = check.instance(rparam.Type.Pos(), baseType, targs, nil, check.context())
291 check.recordInstance(rbase, targs, recvType)
292
293 // Reestablish pointerness if needed (but avoid a pointer to an invalid type).
294 if rptr && isValid(recvType) {
295 recvType = NewPointer(recvType)
296 }
297
298 check.recordParenthesizedRecvTypes(rparam.Type, recvType)
299 }
300 }
301
302 // Make sure we have no more than one receiver name.
303 var rname *ast.Ident
304 if n := len(rparam.Names); n >= 1 {
305 if n > 1 {
306 check.error(rparam.Names[n-1], InvalidRecv, "method has multiple receivers")
307 }
308 rname = rparam.Names[0]
309 }
310
311 // Create the receiver parameter.
312 // recvType is invalid if baseType was never set.
313 var recv *Var
314 if rname != nil && rname.Name != "" {
315 // named receiver
316 recv = newVar(RecvVar, rname.Pos(), check.pkg, rname.Name, recvType)
317 // In this case, the receiver is declared by the caller
318 // because it must be declared after any type parameters
319 // (otherwise it might shadow one of them).
320 } else {
321 // anonymous receiver
322 recv = newVar(RecvVar, rparam.Pos(), check.pkg, "", recvType)
323 check.recordImplicit(rparam, recv)
324 }
325
326 // Delay validation of receiver type as it may cause premature expansion of types
327 // the receiver type is dependent on (see go.dev/issue/51232, go.dev/issue/51233).
328 check.later(func() {
329 check.validRecv(rbase, recv)
330 }).describef(recv, "validRecv(%s)", recv)
331
332 return recv, recvTParamsList
333 }
334
335 func unpointer(t Type) Type {
336 for {
337 p, _ := t.(*Pointer)
338 if p == nil {
339 return t
340 }
341 t = p.base
342 }
343 }
344
345 // recordParenthesizedRecvTypes records parenthesized intermediate receiver type
346 // expressions that all map to the same type, by recursively unpacking expr and
347 // recording the corresponding type for it. Example:
348 //
349 // expression --> type
350 // ----------------------
351 // (*(T[P])) *T[P]
352 // *(T[P]) *T[P]
353 // (T[P]) T[P]
354 // T[P] T[P]
355 func (check *Checker) recordParenthesizedRecvTypes(expr ast.Expr, typ Type) {
356 for {
357 check.recordTypeAndValue(expr, typexpr, typ, nil)
358 switch e := expr.(type) {
359 case *ast.ParenExpr:
360 expr = e.X
361 case *ast.StarExpr:
362 expr = e.X
363 // In a correct program, typ must be an unnamed
364 // pointer type. But be careful and don't panic.
365 ptr, _ := typ.(*Pointer)
366 if ptr == nil {
367 return // something is wrong
368 }
369 typ = ptr.base
370 default:
371 return // cannot unpack any further
372 }
373 }
374 }
375
376 // collectParams collects (but does not declare) all parameter/result
377 // variables of list and returns the list of names and corresponding
378 // variables, and whether the (parameter) list is variadic.
379 // Anonymous parameters are recorded with nil names.
380 func (check *Checker) collectParams(kind VarKind, list *ast.FieldList) (names []*ast.Ident, params []*Var, variadic bool) {
381 if list == nil {
382 return
383 }
384
385 var named, anonymous bool
386 for i, field := range list.List {
387 ftype := field.Type
388 if t, _ := ftype.(*ast.Ellipsis); t != nil {
389 ftype = t.Elt
390 if kind == ParamVar && i == len(list.List)-1 && len(field.Names) <= 1 {
391 variadic = true
392 } else {
393 check.softErrorf(t, InvalidSyntaxTree, "invalid use of ...")
394 // ignore ... and continue
395 }
396 }
397 typ := check.varType(ftype)
398 // The parser ensures that f.Tag is nil and we don't
399 // care if a constructed AST contains a non-nil tag.
400 if len(field.Names) > 0 {
401 // named parameter
402 for _, name := range field.Names {
403 if name.Name == "" {
404 check.error(name, InvalidSyntaxTree, "anonymous parameter")
405 // ok to continue
406 }
407 par := newVar(kind, name.Pos(), check.pkg, name.Name, typ)
408 // named parameter is declared by caller
409 names = append(names, name)
410 params = append(params, par)
411 }
412 named = true
413 } else {
414 // anonymous parameter
415 par := newVar(kind, ftype.Pos(), check.pkg, "", typ)
416 check.recordImplicit(field, par)
417 names = append(names, nil)
418 params = append(params, par)
419 anonymous = true
420 }
421 }
422
423 if named && anonymous {
424 check.error(list, InvalidSyntaxTree, "list contains both named and anonymous parameters")
425 // ok to continue
426 }
427
428 // For a variadic function, change the last parameter's type from T to []T.
429 // Since we type-checked T rather than ...T, we also need to retro-actively
430 // record the type for ...T.
431 if variadic {
432 last := params[len(params)-1]
433 last.typ = &Slice{elem: last.typ}
434 check.recordTypeAndValue(list.List[len(list.List)-1].Type, typexpr, last.typ, nil)
435 }
436
437 return
438 }
439
440 // declareParams declares each named parameter in the current scope.
441 func (check *Checker) declareParams(names []*ast.Ident, params []*Var, scopePos token.Pos) {
442 for i, name := range names {
443 if name != nil && name.Name != "" {
444 check.declare(check.scope, name, params[i], scopePos)
445 }
446 }
447 }
448
449 // validRecv verifies that the receiver satisfies its respective spec requirements
450 // and reports an error otherwise.
451 func (check *Checker) validRecv(pos positioner, recv *Var) {
452 // spec: "The receiver type must be of the form T or *T where T is a type name."
453 rtyp, _ := deref(recv.typ)
454 atyp := Unalias(rtyp)
455 if !isValid(atyp) {
456 return // error was reported before
457 }
458 // spec: "The type denoted by T is called the receiver base type; it must not
459 // be a pointer or interface type and it must be declared in the same package
460 // as the method."
461 switch T := atyp.(type) {
462 case *Named:
463 if T.obj.pkg != check.pkg || isCGoTypeObj(check.fset, T.obj) {
464 check.errorf(pos, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
465 break
466 }
467 var cause string
468 switch u := T.under().(type) {
469 case *Basic:
470 // unsafe.Pointer is treated like a regular pointer
471 if u.kind == UnsafePointer {
472 cause = "unsafe.Pointer"
473 }
474 case *Pointer, *Interface:
475 cause = "pointer or interface type"
476 case *TypeParam:
477 // The underlying type of a receiver base type cannot be a
478 // type parameter: "type T[P any] P" is not a valid declaration.
479 panic("unreachable")
480 }
481 if cause != "" {
482 check.errorf(pos, InvalidRecv, "invalid receiver type %s (%s)", rtyp, cause)
483 }
484 case *Basic:
485 check.errorf(pos, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
486 default:
487 check.errorf(pos, InvalidRecv, "invalid receiver type %s", recv.typ)
488 }
489 }
490
491 // isCGoTypeObj reports whether the given type name was created by cgo.
492 func isCGoTypeObj(fset *token.FileSet, obj *TypeName) bool {
493 return strings.HasPrefix(obj.name, "_Ctype_") ||
494 strings.HasPrefix(filepath.Base(fset.File(obj.pos).Name()), "_cgo_")
495 }