Debian Codegraph @

src/cmd/compile/internal/types2/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 types2
6
7 import (
8 "cmd/compile/internal/syntax"
9 "fmt"
10 . "internal/types/errors"
11 "path/filepath"
12 "strings"
13 )
14
15 // ----------------------------------------------------------------------------
16 // API
17
18 // A Signature represents a (non-builtin) function or method type.
19 // The receiver is ignored when comparing signatures for identity.
20 type Signature struct {
21 // We need to keep the scope in Signature (rather than passing it around
22 // and store it in the Func Object) because when type-checking a function
23 // literal we call the general type checker which returns a general Type.
24 // We then unpack the *Signature and use the scope for the literal body.
25 rparams *TypeParamList // receiver type parameters from left to right, or nil
26 tparams *TypeParamList // type parameters from left to right, or nil
27 scope *Scope // function scope for package-local and non-instantiated signatures; nil otherwise
28 recv *Var // nil if not a method
29 params *Tuple // (incoming) parameters from left to right; or nil
30 results *Tuple // (outgoing) results from left to right; or nil
31 variadic bool // true if the last parameter's type is of the form ...T
32
33 // If variadic, the last element of params ordinarily has an
34 // unnamed Slice type. As a special case, in a call to append,
35 // it may be string, or a TypeParam T whose typeset ⊇ {string, []byte}.
36 // It may even be a named []byte type if a client instantiates
37 // T at such a type.
38 }
39
40 // NewSignatureType creates a new function type for the given receiver,
41 // receiver type parameters, type parameters, parameters, and results.
42 //
43 // If variadic is set, params must hold at least one parameter and the
44 // last parameter must be an unnamed slice or a type parameter whose
45 // type set has an unnamed slice as common underlying type.
46 //
47 // As a special case, to support append([]byte, str...), for variadic
48 // signatures the last parameter may also be a string type, or a type
49 // parameter containing a mix of byte slices and string types in its
50 // type set. It may even be a named []byte slice type resulting from
51 // substitution of such a type parameter.
52 //
53 // If recv is non-nil, typeParams must be empty. If recvTypeParams is
54 // non-empty, recv must be non-nil.
55 func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature {
56 if variadic {
57 n := params.Len()
58 if n == 0 {
59 panic("variadic function must have at least one parameter")
60 }
61 last := params.At(n - 1).typ
62 var S *Slice
63 for t := range typeset(last) {
64 if t == nil {
65 break
66 }
67 var s *Slice
68 if isString(t) {
69 s = NewSlice(universeByte)
70 } else {
71 // Variadic Go functions have a last parameter of type []T,
72 // suggesting we should reject a named slice type B here.
73 //
74 // However, a call to built-in append(slice, x...)
75 // where x has a TypeParam type [T ~string | ~[]byte],
76 // has the type func([]byte, T). Since a client may
77 // instantiate this type at T=B, we must permit
78 // named slice types, even when this results in a
79 // signature func([]byte, B) where type B []byte.
80 //
81 // (The caller of NewSignatureType may have no way to
82 // know that it is dealing with the append special case.)
83 s, _ = t.Underlying().(*Slice)
84 }
85 if S == nil {
86 S = s
87 } else if s == nil || !Identical(S, s) {
88 S = nil
89 break
90 }
91 }
92 if S == nil {
93 panic(fmt.Sprintf("got %s, want variadic parameter of slice or string type", last))
94 }
95 }
96 sig := &Signature{recv: recv, params: params, results: results, variadic: variadic}
97 if len(recvTypeParams) != 0 {
98 if recv == nil {
99 panic("function with receiver type parameters must have a receiver")
100 }
101 sig.rparams = bindTParams(recvTypeParams)
102 }
103 if len(typeParams) != 0 {
104 if recv != nil {
105 panic("function with type parameters cannot have a receiver")
106 }
107 sig.tparams = bindTParams(typeParams)
108 }
109 return sig
110 }
111
112 // Recv returns the receiver of signature s (if a method), or nil if a
113 // function. It is ignored when comparing signatures for identity.
114 //
115 // For an abstract method, Recv returns the enclosing interface either
116 // as a *[Named] or an *[Interface]. Due to embedding, an interface may
117 // contain methods whose receiver type is a different interface.
118 func (s *Signature) Recv() *Var { return s.recv }
119
120 // TypeParams returns the type parameters of signature s, or nil.
121 func (s *Signature) TypeParams() *TypeParamList { return s.tparams }
122
123 // RecvTypeParams returns the receiver type parameters of signature s, or nil.
124 func (s *Signature) RecvTypeParams() *TypeParamList { return s.rparams }
125
126 // Params returns the parameters of signature s, or nil.
127 // See [NewSignatureType] for details of variadic functions.
128 func (s *Signature) Params() *Tuple { return s.params }
129
130 // Results returns the results of signature s, or nil.
131 func (s *Signature) Results() *Tuple { return s.results }
132
133 // Variadic reports whether the signature s is variadic.
134 func (s *Signature) Variadic() bool { return s.variadic }
135
136 func (s *Signature) Underlying() Type { return s }
137 func (s *Signature) String() string { return TypeString(s, nil) }
138
139 // ----------------------------------------------------------------------------
140 // Implementation
141
142 // funcType type-checks a function or method type.
143 func (check *Checker) funcType(sig *Signature, recvPar *syntax.Field, tparams []*syntax.Field, ftyp *syntax.FuncType) {
144 check.openScope(ftyp, "function")
145 check.scope.isFunc = true
146 check.recordScope(ftyp, check.scope)
147 sig.scope = check.scope
148 defer check.closeScope()
149
150 // collect method receiver, if any
151 var recv *Var
152 var rparams *TypeParamList
153 if recvPar != nil {
154 // all type parameters' scopes start after the method name
155 scopePos := ftyp.Pos()
156 recv, rparams = check.collectRecv(recvPar, scopePos)
157 }
158
159 // collect and declare function type parameters
160 if tparams != nil {
161 // The parser will complain about invalid type parameters for methods.
162 check.collectTypeParams(&sig.tparams, tparams)
163 }
164
165 // collect ordinary and result parameters
166 pnames, params, variadic := check.collectParams(ParamVar, ftyp.ParamList)
167 rnames, results, _ := check.collectParams(ResultVar, ftyp.ResultList)
168
169 // declare named receiver, ordinary, and result parameters
170 scopePos := syntax.EndPos(ftyp) // all parameter's scopes start after the signature
171 if recv != nil && recv.name != "" {
172 check.declare(check.scope, recvPar.Name, 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 *syntax.Field, scopePos syntax.Pos) (*Var, *TypeParamList) {
188 // Unpack the receiver parameter which is of the form
189 //
190 // "(" [rname] ["*"] 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 types2.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(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 // Create the receiver parameter.
303 // recvType is invalid if baseType was never set.
304 var recv *Var
305 if rname := rparam.Name; rname != nil && rname.Value != "" {
306 // named receiver
307 recv = newVar(RecvVar, rname.Pos(), check.pkg, rname.Value, recvType)
308 // In this case, the receiver is declared by the caller
309 // because it must be declared after any type parameters
310 // (otherwise it might shadow one of them).
311 } else {
312 // anonymous receiver
313 recv = newVar(RecvVar, rparam.Pos(), check.pkg, "", recvType)
314 check.recordImplicit(rparam, recv)
315 }
316
317 // Delay validation of receiver type as it may cause premature expansion of types
318 // the receiver type is dependent on (see go.dev/issue/51232, go.dev/issue/51233).
319 check.later(func() {
320 check.validRecv(rbase, recv)
321 }).describef(recv, "validRecv(%s)", recv)
322
323 return recv, recvTParamsList
324 }
325
326 func unpointer(t Type) Type {
327 for {
328 p, _ := t.(*Pointer)
329 if p == nil {
330 return t
331 }
332 t = p.base
333 }
334 }
335
336 // recordParenthesizedRecvTypes records parenthesized intermediate receiver type
337 // expressions that all map to the same type, by recursively unpacking expr and
338 // recording the corresponding type for it. Example:
339 //
340 // expression --> type
341 // ----------------------
342 // (*(T[P])) *T[P]
343 // *(T[P]) *T[P]
344 // (T[P]) T[P]
345 // T[P] T[P]
346 func (check *Checker) recordParenthesizedRecvTypes(expr syntax.Expr, typ Type) {
347 for {
348 check.recordTypeAndValue(expr, typexpr, typ, nil)
349 switch e := expr.(type) {
350 case *syntax.ParenExpr:
351 expr = e.X
352 case *syntax.Operation:
353 if e.Op == syntax.Mul && e.Y == nil {
354 expr = e.X
355 // In a correct program, typ must be an unnamed
356 // pointer type. But be careful and don't panic.
357 ptr, _ := typ.(*Pointer)
358 if ptr == nil {
359 return // something is wrong
360 }
361 typ = ptr.base
362 break
363 }
364 return // cannot unpack any further
365 default:
366 return // cannot unpack any further
367 }
368 }
369 }
370
371 // collectParams collects (but does not declare) all parameter/result
372 // variables of list and returns the list of names and corresponding
373 // variables, and whether the (parameter) list is variadic.
374 // Anonymous parameters are recorded with nil names.
375 func (check *Checker) collectParams(kind VarKind, list []*syntax.Field) (names []*syntax.Name, params []*Var, variadic bool) {
376 if list == nil {
377 return
378 }
379
380 var named, anonymous bool
381
382 var typ Type
383 var prev syntax.Expr
384 for i, field := range list {
385 ftype := field.Type
386 // type-check type of grouped fields only once
387 if ftype != prev {
388 prev = ftype
389 if t, _ := ftype.(*syntax.DotsType); t != nil {
390 ftype = t.Elem
391 if kind == ParamVar && i == len(list)-1 {
392 variadic = true
393 } else {
394 check.error(t, InvalidSyntaxTree, "invalid use of ...")
395 // ignore ... and continue
396 }
397 }
398 typ = check.varType(ftype)
399 }
400 // The parser ensures that f.Tag is nil and we don't
401 // care if a constructed AST contains a non-nil tag.
402 if field.Name != nil {
403 // named parameter
404 name := field.Name.Value
405 if name == "" {
406 check.error(field.Name, InvalidSyntaxTree, "anonymous parameter")
407 // ok to continue
408 }
409 par := newVar(kind, field.Name.Pos(), check.pkg, name, typ)
410 // named parameter is declared by caller
411 names = append(names, field.Name)
412 params = append(params, par)
413 named = true
414 } else {
415 // anonymous parameter
416 par := newVar(kind, field.Pos(), check.pkg, "", typ)
417 check.recordImplicit(field, par)
418 names = append(names, nil)
419 params = append(params, par)
420 anonymous = true
421 }
422 }
423
424 if named && anonymous {
425 check.error(list[0], InvalidSyntaxTree, "list contains both named and anonymous parameters")
426 // ok to continue
427 }
428
429 // For a variadic function, change the last parameter's type from T to []T.
430 // Since we type-checked T rather than ...T, we also need to retro-actively
431 // record the type for ...T.
432 if variadic {
433 last := params[len(params)-1]
434 last.typ = &Slice{elem: last.typ}
435 check.recordTypeAndValue(list[len(list)-1].Type, typexpr, last.typ, nil)
436 }
437
438 return
439 }
440
441 // declareParams declares each named parameter in the current scope.
442 func (check *Checker) declareParams(names []*syntax.Name, params []*Var, scopePos syntax.Pos) {
443 for i, name := range names {
444 if name != nil && name.Value != "" {
445 check.declare(check.scope, name, params[i], scopePos)
446 }
447 }
448 }
449
450 // validRecv verifies that the receiver satisfies its respective spec requirements
451 // and reports an error otherwise.
452 func (check *Checker) validRecv(pos poser, recv *Var) {
453 // spec: "The receiver type must be of the form T or *T where T is a type name."
454 rtyp, _ := deref(recv.typ)
455 atyp := Unalias(rtyp)
456 if !isValid(atyp) {
457 return // error was reported before
458 }
459 // spec: "The type denoted by T is called the receiver base type; it must not
460 // be a pointer or interface type and it must be declared in the same package
461 // as the method."
462 switch T := atyp.(type) {
463 case *Named:
464 if T.obj.pkg != check.pkg || isCGoTypeObj(T.obj) {
465 check.errorf(pos, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
466 break
467 }
468 var cause string
469 switch u := T.Underlying().(type) {
470 case *Basic:
471 // unsafe.Pointer is treated like a regular pointer
472 if u.kind == UnsafePointer {
473 cause = "unsafe.Pointer"
474 }
475 case *Pointer, *Interface:
476 cause = "pointer or interface type"
477 case *TypeParam:
478 // The underlying type of a receiver base type cannot be a
479 // type parameter: "type T[P any] P" is not a valid declaration.
480 panic("unreachable")
481 }
482 if cause != "" {
483 check.errorf(pos, InvalidRecv, "invalid receiver type %s (%s)", rtyp, cause)
484 }
485 case *Basic:
486 check.errorf(pos, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
487 default:
488 check.errorf(pos, InvalidRecv, "invalid receiver type %s", recv.typ)
489 }
490 }
491
492 // isCGoTypeObj reports whether the given type name was created by cgo.
493 func isCGoTypeObj(obj *TypeName) bool {
494 return strings.HasPrefix(obj.name, "_Ctype_") ||
495 strings.HasPrefix(filepath.Base(obj.pos.FileBase().Filename()), "_cgo_")
496 }