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.
8 "cmd/compile/internal/syntax"
10 . "internal/types/errors"
13 // ----------------------------------------------------------------------------
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)
32 // NewSignatureType creates a new function type for the given receiver,
33 // receiver type parameters, type parameters, parameters, and results. If
34 // variadic is set, params must hold at least one parameter and the last
35 // parameter's core type must be of unnamed slice or bytestring type.
36 // If recv is non-nil, typeParams must be empty. If recvTypeParams is
37 // non-empty, recv must be non-nil.
38 func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature {
42 panic("variadic function must have at least one parameter")
44 core := coreString(params.At(n - 1).typ)
45 if _, ok := core.(*Slice); !ok && !isString(core) {
46 panic(fmt.Sprintf("got %s, want variadic parameter with unnamed slice type or string as core type", core.String()))
49 sig := &Signature{recv: recv, params: params, results: results, variadic: variadic}
50 if len(recvTypeParams) != 0 {
52 panic("function with receiver type parameters must have a receiver")
54 sig.rparams = bindTParams(recvTypeParams)
56 if len(typeParams) != 0 {
58 panic("function with type parameters cannot have a receiver")
60 sig.tparams = bindTParams(typeParams)
65 // Recv returns the receiver of signature s (if a method), or nil if a
66 // function. It is ignored when comparing signatures for identity.
68 // For an abstract method, Recv returns the enclosing interface either
69 // as a *Named or an *Interface. Due to embedding, an interface may
70 // contain methods whose receiver type is a different interface.
71 func (s *Signature) Recv() *Var { return s.recv }
73 // TypeParams returns the type parameters of signature s, or nil.
74 func (s *Signature) TypeParams() *TypeParamList { return s.tparams }
76 // SetTypeParams sets the type parameters of signature s.
77 func (s *Signature) SetTypeParams(tparams []*TypeParam) { s.tparams = bindTParams(tparams) }
79 // RecvTypeParams returns the receiver type parameters of signature s, or nil.
80 func (s *Signature) RecvTypeParams() *TypeParamList { return s.rparams }
82 // Params returns the parameters of signature s, or nil.
83 func (s *Signature) Params() *Tuple { return s.params }
85 // Results returns the results of signature s, or nil.
86 func (s *Signature) Results() *Tuple { return s.results }
88 // Variadic reports whether the signature s is variadic.
89 func (s *Signature) Variadic() bool { return s.variadic }
91 func (s *Signature) Underlying() Type { return s }
92 func (s *Signature) String() string { return TypeString(s, nil) }
94 // ----------------------------------------------------------------------------
97 // funcType type-checks a function or method type.
98 func (check *Checker) funcType(sig *Signature, recvPar *syntax.Field, tparams []*syntax.Field, ftyp *syntax.FuncType) {
99 check.openScope(ftyp, "function")
100 check.scope.isFunc = true
101 check.recordScope(ftyp, check.scope)
102 sig.scope = check.scope
103 defer check.closeScope()
106 // collect generic receiver type parameters, if any
107 // - a receiver type parameter is like any other type parameter, except that it is declared implicitly
108 // - the receiver specification acts as local declaration for its type parameters, which may be blank
109 _, rname, rparams := check.unpackRecv(recvPar.Type, true)
110 if len(rparams) > 0 {
111 tparams := make([]*TypeParam, len(rparams))
112 for i, rparam := range rparams {
113 tparams[i] = check.declareTypeParam(rparam)
115 sig.rparams = bindTParams(tparams)
116 // Blank identifiers don't get declared, so naive type-checking of the
117 // receiver type expression would fail in Checker.collectParams below,
118 // when Checker.ident cannot resolve the _ to a type.
120 // Checker.recvTParamMap maps these blank identifiers to their type parameter
121 // types, so that they may be resolved in Checker.ident when they fail
122 // lookup in the scope.
123 for i, p := range rparams {
125 if check.recvTParamMap == nil {
126 check.recvTParamMap = make(map[*syntax.Name]*TypeParam)
128 check.recvTParamMap[p] = tparams[i]
131 // determine receiver type to get its type parameters
132 // and the respective type parameter bounds
133 var recvTParams []*TypeParam
135 // recv should be a Named type (otherwise an error is reported elsewhere)
136 // Also: Don't report an error via genericType since it will be reported
137 // again when we type-check the signature.
138 // TODO(gri) maybe the receiver should be marked as invalid instead?
139 if recv := asNamed(check.genericType(rname, nil)); recv != nil {
140 recvTParams = recv.TypeParams().list()
143 // provide type parameter bounds
144 if len(tparams) == len(recvTParams) {
145 smap := makeRenameMap(recvTParams, tparams)
146 for i, tpar := range tparams {
147 recvTPar := recvTParams[i]
148 check.mono.recordCanon(tpar, recvTPar)
149 // recvTPar.bound is (possibly) parameterized in the context of the
150 // receiver type declaration. Substitute parameters for the current
152 tpar.bound = check.subst(tpar.obj.pos, recvTPar.bound, smap, nil, check.context())
154 } else if len(tparams) < len(recvTParams) {
155 // Reporting an error here is a stop-gap measure to avoid crashes in the
156 // compiler when a type parameter/argument cannot be inferred later. It
157 // may lead to follow-on errors (see issues go.dev/issue/51339, go.dev/issue/51343).
158 // TODO(gri) find a better solution
159 got := measure(len(tparams), "type parameter")
160 check.errorf(recvPar, BadRecv, "got %s, but receiver base type declares %d", got, len(recvTParams))
166 // The parser will complain about invalid type parameters for methods.
167 check.collectTypeParams(&sig.tparams, tparams)
170 // Value (non-type) parameters' scope starts in the function body. Use a temporary scope for their
171 // declarations and then squash that scope into the parent scope (and report any redeclarations at
173 scope := NewScope(check.scope, nopos, nopos, "function body (temp. scope)")
174 var recvList []*Var // TODO(gri) remove the need for making a list here
176 recvList, _ = check.collectParams(scope, []*syntax.Field{recvPar}, false) // use rewritten receiver type, if any
178 params, variadic := check.collectParams(scope, ftyp.ParamList, true)
179 results, _ := check.collectParams(scope, ftyp.ResultList, false)
180 scope.Squash(func(obj, alt Object) {
182 err.code = DuplicateDecl
183 err.errorf(obj, "%s redeclared in this block", obj.Name())
184 err.recordAltDecl(alt)
189 // recv parameter list present (may be empty)
190 // spec: "The receiver is specified via an extra parameter section preceding the
191 // method name. That parameter section must declare a single parameter, the receiver."
193 switch len(recvList) {
195 // error reported by resolver
196 recv = NewParam(nopos, nil, "", Typ[Invalid]) // ignore recv below
198 // more than one receiver
199 check.error(recvList[len(recvList)-1].Pos(), InvalidRecv, "method must have exactly one receiver")
200 fallthrough // continue with first receiver
206 // Delay validation of receiver type as it may cause premature expansion
207 // of types the receiver type is dependent on (see issues go.dev/issue/51232, go.dev/issue/51233).
209 // spec: "The receiver type must be of the form T or *T where T is a type name."
210 rtyp, _ := deref(recv.typ)
211 atyp := Unalias(rtyp)
213 return // error was reported before
215 // spec: "The type denoted by T is called the receiver base type; it must not
216 // be a pointer or interface type and it must be declared in the same package
218 switch T := atyp.(type) {
220 // The receiver type may be an instantiated type referred to
221 // by an alias (which cannot have receiver parameters for now).
222 if T.TypeArgs() != nil && sig.RecvTypeParams() == nil {
223 check.errorf(recv, InvalidRecv, "cannot define new methods on instantiated type %s", rtyp)
226 if T.obj.pkg != check.pkg {
227 check.errorf(recv, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
231 switch u := T.under().(type) {
233 // unsafe.Pointer is treated like a regular pointer
234 if u.kind == UnsafePointer {
235 cause = "unsafe.Pointer"
237 case *Pointer, *Interface:
238 cause = "pointer or interface type"
240 // The underlying type of a receiver base type cannot be a
241 // type parameter: "type T[P any] P" is not a valid declaration.
245 check.errorf(recv, InvalidRecv, "invalid receiver type %s (%s)", rtyp, cause)
248 check.errorf(recv, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
250 check.errorf(recv, InvalidRecv, "invalid receiver type %s", recv.typ)
252 }).describef(recv, "validate receiver %s", recv)
255 sig.params = NewTuple(params...)
256 sig.results = NewTuple(results...)
257 sig.variadic = variadic
260 // collectParams declares the parameters of list in scope and returns the corresponding
262 func (check *Checker) collectParams(scope *Scope, list []*syntax.Field, variadicOk bool) (params []*Var, variadic bool) {
267 var named, anonymous bool
271 for i, field := range list {
273 // type-check type of grouped fields only once
276 if t, _ := ftype.(*syntax.DotsType); t != nil {
278 if variadicOk && i == len(list)-1 {
281 check.softErrorf(t, MisplacedDotDotDot, "can only use ... with final parameter in list")
282 // ignore ... and continue
285 typ = check.varType(ftype)
287 // The parser ensures that f.Tag is nil and we don't
288 // care if a constructed AST contains a non-nil tag.
289 if field.Name != nil {
291 name := field.Name.Value
293 check.error(field.Name, InvalidSyntaxTree, "anonymous parameter")
296 par := NewParam(field.Name.Pos(), check.pkg, name, typ)
297 check.declare(scope, field.Name, par, scope.pos)
298 params = append(params, par)
301 // anonymous parameter
302 par := NewParam(field.Pos(), check.pkg, "", typ)
303 check.recordImplicit(field, par)
304 params = append(params, par)
309 if named && anonymous {
310 check.error(list[0], InvalidSyntaxTree, "list contains both named and anonymous parameters")
314 // For a variadic function, change the last parameter's type from T to []T.
315 // Since we type-checked T rather than ...T, we also need to retro-actively
316 // record the type for ...T.
318 last := params[len(params)-1]
319 last.typ = &Slice{elem: last.typ}
320 check.recordTypeAndValue(list[len(list)-1].Type, typexpr, last.typ, nil)