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"
12 // ----------------------------------------------------------------------------
15 // A Signature represents a (non-builtin) function or method type.
16 // The receiver is ignored when comparing signatures for identity.
17 type Signature struct {
18 // We need to keep the scope in Signature (rather than passing it around
19 // and store it in the Func Object) because when type-checking a function
20 // literal we call the general type checker which returns a general Type.
21 // We then unpack the *Signature and use the scope for the literal body.
22 rparams *TypeParamList // receiver type parameters from left to right, or nil
23 tparams *TypeParamList // type parameters from left to right, or nil
24 scope *Scope // function scope for package-local and non-instantiated signatures; nil otherwise
25 recv *Var // nil if not a method
26 params *Tuple // (incoming) parameters from left to right; or nil
27 results *Tuple // (outgoing) results from left to right; or nil
28 variadic bool // true if the last parameter's type is of the form ...T (or string, for append built-in only)
31 // NewSignatureType creates a new function type for the given receiver,
32 // receiver type parameters, type parameters, parameters, and results. If
33 // variadic is set, params must hold at least one parameter and the last
34 // parameter's core type must be of unnamed slice or bytestring type.
35 // If recv is non-nil, typeParams must be empty. If recvTypeParams is
36 // non-empty, recv must be non-nil.
37 func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature {
41 panic("variadic function must have at least one parameter")
43 core := coreString(params.At(n - 1).typ)
44 if _, ok := core.(*Slice); !ok && !isString(core) {
45 panic(fmt.Sprintf("got %s, want variadic parameter with unnamed slice type or string as core type", core.String()))
48 sig := &Signature{recv: recv, params: params, results: results, variadic: variadic}
49 if len(recvTypeParams) != 0 {
51 panic("function with receiver type parameters must have a receiver")
53 sig.rparams = bindTParams(recvTypeParams)
55 if len(typeParams) != 0 {
57 panic("function with type parameters cannot have a receiver")
59 sig.tparams = bindTParams(typeParams)
64 // Recv returns the receiver of signature s (if a method), or nil if a
65 // function. It is ignored when comparing signatures for identity.
67 // For an abstract method, Recv returns the enclosing interface either
68 // as a *Named or an *Interface. Due to embedding, an interface may
69 // contain methods whose receiver type is a different interface.
70 func (s *Signature) Recv() *Var { return s.recv }
72 // TypeParams returns the type parameters of signature s, or nil.
73 func (s *Signature) TypeParams() *TypeParamList { return s.tparams }
75 // SetTypeParams sets the type parameters of signature s.
76 func (s *Signature) SetTypeParams(tparams []*TypeParam) { s.tparams = bindTParams(tparams) }
78 // RecvTypeParams returns the receiver type parameters of signature s, or nil.
79 func (s *Signature) RecvTypeParams() *TypeParamList { return s.rparams }
81 // Params returns the parameters of signature s, or nil.
82 func (s *Signature) Params() *Tuple { return s.params }
84 // Results returns the results of signature s, or nil.
85 func (s *Signature) Results() *Tuple { return s.results }
87 // Variadic reports whether the signature s is variadic.
88 func (s *Signature) Variadic() bool { return s.variadic }
90 func (s *Signature) Underlying() Type { return s }
91 func (s *Signature) String() string { return TypeString(s, nil) }
93 // ----------------------------------------------------------------------------
96 // funcType type-checks a function or method type.
97 func (check *Checker) funcType(sig *Signature, recvPar *syntax.Field, tparams []*syntax.Field, ftyp *syntax.FuncType) {
98 check.openScope(ftyp, "function")
99 check.scope.isFunc = true
100 check.recordScope(ftyp, check.scope)
101 sig.scope = check.scope
102 defer check.closeScope()
105 // collect generic receiver type parameters, if any
106 // - a receiver type parameter is like any other type parameter, except that it is declared implicitly
107 // - the receiver specification acts as local declaration for its type parameters, which may be blank
108 _, rname, rparams := check.unpackRecv(recvPar.Type, true)
109 if len(rparams) > 0 {
110 tparams := make([]*TypeParam, len(rparams))
111 for i, rparam := range rparams {
112 tparams[i] = check.declareTypeParam(rparam)
114 sig.rparams = bindTParams(tparams)
115 // Blank identifiers don't get declared, so naive type-checking of the
116 // receiver type expression would fail in Checker.collectParams below,
117 // when Checker.ident cannot resolve the _ to a type.
119 // Checker.recvTParamMap maps these blank identifiers to their type parameter
120 // types, so that they may be resolved in Checker.ident when they fail
121 // lookup in the scope.
122 for i, p := range rparams {
124 if check.recvTParamMap == nil {
125 check.recvTParamMap = make(map[*syntax.Name]*TypeParam)
127 check.recvTParamMap[p] = tparams[i]
130 // determine receiver type to get its type parameters
131 // and the respective type parameter bounds
132 var recvTParams []*TypeParam
134 // recv should be a Named type (otherwise an error is reported elsewhere)
135 // Also: Don't report an error via genericType since it will be reported
136 // again when we type-check the signature.
137 // TODO(gri) maybe the receiver should be marked as invalid instead?
138 if recv, _ := check.genericType(rname, nil).(*Named); recv != nil {
139 recvTParams = recv.TypeParams().list()
142 // provide type parameter bounds
143 if len(tparams) == len(recvTParams) {
144 smap := makeRenameMap(recvTParams, tparams)
145 for i, tpar := range tparams {
146 recvTPar := recvTParams[i]
147 check.mono.recordCanon(tpar, recvTPar)
148 // recvTPar.bound is (possibly) parameterized in the context of the
149 // receiver type declaration. Substitute parameters for the current
151 tpar.bound = check.subst(tpar.obj.pos, recvTPar.bound, smap, nil, check.context())
153 } else if len(tparams) < len(recvTParams) {
154 // Reporting an error here is a stop-gap measure to avoid crashes in the
155 // compiler when a type parameter/argument cannot be inferred later. It
156 // may lead to follow-on errors (see issues #51339, #51343).
157 // TODO(gri) find a better solution
158 got := measure(len(tparams), "type parameter")
159 check.errorf(recvPar, _BadRecv, "got %s, but receiver base type declares %d", got, len(recvTParams))
165 // The parser will complain about invalid type parameters for methods.
166 check.collectTypeParams(&sig.tparams, tparams)
169 // Value (non-type) parameters' scope starts in the function body. Use a temporary scope for their
170 // declarations and then squash that scope into the parent scope (and report any redeclarations at
172 scope := NewScope(check.scope, nopos, nopos, "function body (temp. scope)")
173 var recvList []*Var // TODO(gri) remove the need for making a list here
175 recvList, _ = check.collectParams(scope, []*syntax.Field{recvPar}, false) // use rewritten receiver type, if any
177 params, variadic := check.collectParams(scope, ftyp.ParamList, true)
178 results, _ := check.collectParams(scope, ftyp.ResultList, false)
179 scope.Squash(func(obj, alt Object) {
181 err.errorf(obj, "%s redeclared in this block", obj.Name())
182 err.recordAltDecl(alt)
187 // recv parameter list present (may be empty)
188 // spec: "The receiver is specified via an extra parameter section preceding the
189 // method name. That parameter section must declare a single parameter, the receiver."
191 switch len(recvList) {
193 // error reported by resolver
194 recv = NewParam(nopos, nil, "", Typ[Invalid]) // ignore recv below
196 // more than one receiver
197 check.error(recvList[len(recvList)-1].Pos(), _InvalidRecv, "method must have exactly one receiver")
198 fallthrough // continue with first receiver
204 // Delay validation of receiver type as it may cause premature expansion
205 // of types the receiver type is dependent on (see issues #51232, #51233).
207 // spec: "The receiver type must be of the form T or *T where T is a type name."
208 rtyp, _ := deref(recv.typ)
209 if rtyp == Typ[Invalid] {
210 return // error was reported before
212 // spec: "The type denoted by T is called the receiver base type; it must not
213 // be a pointer or interface type and it must be declared in the same package
215 switch T := rtyp.(type) {
217 // The receiver type may be an instantiated type referred to
218 // by an alias (which cannot have receiver parameters for now).
219 if T.TypeArgs() != nil && sig.RecvTypeParams() == nil {
220 check.errorf(recv, _InvalidRecv, "cannot define new methods on instantiated type %s", rtyp)
223 if T.obj.pkg != check.pkg {
224 check.errorf(recv, _InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
228 switch u := T.under().(type) {
230 // unsafe.Pointer is treated like a regular pointer
231 if u.kind == UnsafePointer {
232 cause = "unsafe.Pointer"
234 case *Pointer, *Interface:
235 cause = "pointer or interface type"
237 // The underlying type of a receiver base type cannot be a
238 // type parameter: "type T[P any] P" is not a valid declaration.
242 check.errorf(recv, _InvalidRecv, "invalid receiver type %s (%s)", rtyp, cause)
245 check.errorf(recv, _InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
247 check.errorf(recv, _InvalidRecv, "invalid receiver type %s", recv.typ)
249 }).describef(recv, "validate receiver %s", recv)
252 sig.params = NewTuple(params...)
253 sig.results = NewTuple(results...)
254 sig.variadic = variadic
257 // collectParams declares the parameters of list in scope and returns the corresponding
259 func (check *Checker) collectParams(scope *Scope, list []*syntax.Field, variadicOk bool) (params []*Var, variadic bool) {
264 var named, anonymous bool
268 for i, field := range list {
270 // type-check type of grouped fields only once
273 if t, _ := ftype.(*syntax.DotsType); t != nil {
275 if variadicOk && i == len(list)-1 {
278 check.softErrorf(t, _MisplacedDotDotDot, "can only use ... with final parameter in list")
279 // ignore ... and continue
282 typ = check.varType(ftype)
284 // The parser ensures that f.Tag is nil and we don't
285 // care if a constructed AST contains a non-nil tag.
286 if field.Name != nil {
288 name := field.Name.Value
290 check.error(field.Name, 0, invalidAST+"anonymous parameter")
293 par := NewParam(field.Name.Pos(), check.pkg, name, typ)
294 check.declare(scope, field.Name, par, scope.pos)
295 params = append(params, par)
298 // anonymous parameter
299 par := NewParam(field.Pos(), check.pkg, "", typ)
300 check.recordImplicit(field, par)
301 params = append(params, par)
306 if named && anonymous {
307 check.error(list[0], 0, invalidAST+"list contains both named and anonymous parameters")
311 // For a variadic function, change the last parameter's type from T to []T.
312 // Since we type-checked T rather than ...T, we also need to retro-actively
313 // record the type for ...T.
315 last := params[len(params)-1]
316 last.typ = &Slice{elem: last.typ}
317 check.recordTypeAndValue(list[len(list)-1].Type, typexpr, last.typ, nil)