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