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.
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 // 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.
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)
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 {
52 panic("variadic function must have at least one parameter")
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()))
59 sig := &Signature{recv: recv, params: params, results: results, variadic: variadic}
60 if len(recvTypeParams) != 0 {
62 panic("function with receiver type parameters must have a receiver")
64 sig.rparams = bindTParams(recvTypeParams)
66 if len(typeParams) != 0 {
68 panic("function with type parameters cannot have a receiver")
70 sig.tparams = bindTParams(typeParams)
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.
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 }
83 // TypeParams returns the type parameters of signature s, or nil.
84 func (s *Signature) TypeParams() *TypeParamList { return s.tparams }
86 // RecvTypeParams returns the receiver type parameters of signature s, or nil.
87 func (s *Signature) RecvTypeParams() *TypeParamList { return s.rparams }
89 // Params returns the parameters of signature s, or nil.
90 func (s *Signature) Params() *Tuple { return s.params }
92 // Results returns the results of signature s, or nil.
93 func (s *Signature) Results() *Tuple { return s.results }
95 // Variadic reports whether the signature s is variadic.
96 func (s *Signature) Variadic() bool { return s.variadic }
98 func (t *Signature) Underlying() Type { return t }
99 func (t *Signature) String() string { return TypeString(t, nil) }
101 // ----------------------------------------------------------------------------
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()
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.
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 {
129 if check.recvTParamMap == nil {
130 check.recvTParamMap = make(map[*ast.Ident]*TypeParam)
132 check.recvTParamMap[p] = tparams[i]
135 // determine receiver type to get its type parameters
136 // and the respective type parameter bounds
137 var recvTParams []*TypeParam
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()
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
156 tpar.bound = check.subst(tpar.obj.pos, recvTPar.bound, smap, nil, check.context())
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))
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.)
175 check.error(ftyp.TypeParams, InvalidMethodTypeParams, "methods cannot have type parameters")
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
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)
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."
196 switch len(recvList) {
198 // error reported by resolver
199 recv = NewParam(nopos, nil, "", Typ[Invalid]) // ignore recv below
201 // more than one receiver
202 check.error(recvList[len(recvList)-1], InvalidRecv, "method has multiple receivers")
203 fallthrough // continue with first receiver
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).
212 // spec: "The receiver type must be of the form T or *T where T is a type name."
213 rtyp, _ := deref(recv.typ)
215 return // error was reported before
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
220 switch T := rtyp.(type) {
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)
228 if T.obj.pkg != check.pkg {
229 check.errorf(recv, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
233 switch u := T.under().(type) {
235 // unsafe.Pointer is treated like a regular pointer
236 if u.kind == UnsafePointer {
237 cause = "unsafe.Pointer"
239 case *Pointer, *Interface:
240 cause = "pointer or interface type"
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.
247 check.errorf(recv, InvalidRecv, "invalid receiver type %s (%s)", rtyp, cause)
250 check.errorf(recv, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
252 check.errorf(recv, InvalidRecv, "invalid receiver type %s", recv.typ)
254 }).describef(recv, "validate receiver %s", recv)
257 sig.params = NewTuple(params...)
258 sig.results = NewTuple(results...)
259 sig.variadic = variadic
262 // collectParams declares the parameters of list in scope and returns the corresponding
264 func (check *Checker) collectParams(scope *Scope, list *ast.FieldList, variadicOk bool) (params []*Var, variadic bool) {
269 var named, anonymous bool
270 for i, field := range list.List {
272 if t, _ := ftype.(*ast.Ellipsis); t != nil {
274 if variadicOk && i == len(list.List)-1 && len(field.Names) <= 1 {
277 check.softErrorf(t, MisplacedDotDotDot, "can only use ... with final parameter in list")
278 // ignore ... and continue
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 {
286 for _, name := range field.Names {
288 check.error(name, InvalidSyntaxTree, "anonymous parameter")
291 par := NewParam(name.Pos(), check.pkg, name.Name, typ)
292 check.declare(scope, name, par, scope.pos)
293 params = append(params, par)
297 // anonymous parameter
298 par := NewParam(ftype.Pos(), check.pkg, "", typ)
299 check.recordImplicit(field, par)
300 params = append(params, par)
305 if named && anonymous {
306 check.error(list, InvalidSyntaxTree, "list contains both named and anonymous parameters")
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.
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)