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, present for package-local signatures
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 // NewSignature returns a new function type for the given receiver, parameters,
32 // and results, either of which may be nil. If variadic is set, the function
33 // is variadic, it must have at least one parameter, and the last parameter
34 // must be of unnamed slice type.
36 // Deprecated: Use NewSignatureType instead which allows for type parameters.
37 func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature {
38 return NewSignatureType(recv, nil, nil, params, results, variadic)
41 // NewSignatureType creates a new function type for the given receiver,
42 // receiver type parameters, type parameters, parameters, and results. If
43 // variadic is set, params must hold at least one parameter and the last
44 // parameter must be of unnamed slice type. If recv is non-nil, typeParams must
45 // be empty. If recvTypeParams is non-empty, recv must be non-nil.
46 func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature {
50 panic("variadic function must have at least one parameter")
52 if _, ok := params.At(n - 1).typ.(*Slice); !ok {
53 panic("variadic parameter must be of unnamed slice type")
56 sig := &Signature{recv: recv, params: params, results: results, variadic: variadic}
57 if len(recvTypeParams) != 0 {
59 panic("function with receiver type parameters must have a receiver")
61 sig.rparams = bindTParams(recvTypeParams)
63 if len(typeParams) != 0 {
65 panic("function with type parameters cannot have a receiver")
67 sig.tparams = bindTParams(typeParams)
72 // Recv returns the receiver of signature s (if a method), or nil if a
73 // function. It is ignored when comparing signatures for identity.
75 // For an abstract method, Recv returns the enclosing interface either
76 // as a *Named or an *Interface. Due to embedding, an interface may
77 // contain methods whose receiver type is a different interface.
78 func (s *Signature) Recv() *Var { return s.recv }
80 // TypeParams returns the type parameters of signature s, or nil.
81 func (s *Signature) TypeParams() *TypeParamList { return s.tparams }
83 // SetTypeParams sets the type parameters of signature s.
84 func (s *Signature) SetTypeParams(tparams []*TypeParam) { s.tparams = bindTParams(tparams) }
86 // RecvTypeParams returns the receiver type parameters of signature s, or nil.
87 func (s *Signature) RecvTypeParams() *TypeParamList { return s.rparams }
89 // SetRecvTypeParams sets the receiver type params of signature s.
90 func (s *Signature) SetRecvTypeParams(rparams []*TypeParam) { s.rparams = bindTParams(rparams) }
92 // Params returns the parameters of signature s, or nil.
93 func (s *Signature) Params() *Tuple { return s.params }
95 // Results returns the results of signature s, or nil.
96 func (s *Signature) Results() *Tuple { return s.results }
98 // Variadic reports whether the signature s is variadic.
99 func (s *Signature) Variadic() bool { return s.variadic }
101 func (s *Signature) Underlying() Type { return s }
102 func (s *Signature) String() string { return TypeString(s, nil) }
104 // ----------------------------------------------------------------------------
107 // Disabled by default, but enabled when running tests (via types_test.go).
108 var acceptMethodTypeParams bool
110 // funcType type-checks a function or method type.
111 func (check *Checker) funcType(sig *Signature, recvPar *syntax.Field, tparams []*syntax.Field, ftyp *syntax.FuncType) {
112 check.openScope(ftyp, "function")
113 check.scope.isFunc = true
114 check.recordScope(ftyp, check.scope)
115 sig.scope = check.scope
116 defer check.closeScope()
118 var recvTyp syntax.Expr // rewritten receiver type; valid if != nil
120 // collect generic receiver type parameters, if any
121 // - a receiver type parameter is like any other type parameter, except that it is declared implicitly
122 // - the receiver specification acts as local declaration for its type parameters, which may be blank
123 _, rname, rparams := check.unpackRecv(recvPar.Type, true)
124 if len(rparams) > 0 {
125 // Blank identifiers don't get declared and regular type-checking of the instantiated
126 // parameterized receiver type expression fails in Checker.collectParams of receiver.
127 // Identify blank type parameters and substitute each with a unique new identifier named
128 // "n_" (where n is the parameter index) and which cannot conflict with any user-defined
130 var smap map[*syntax.Name]*syntax.Name // substitution map from "_" to "!n" identifiers
131 for i, p := range rparams {
134 new.Value = fmt.Sprintf("%d_", i)
135 rparams[i] = &new // use n_ identifier instead of _ so it can be looked up
137 smap = make(map[*syntax.Name]*syntax.Name)
143 // blank identifiers were found => use rewritten receiver type
144 recvTyp = isubst(recvPar.Type, smap)
146 rlist := make([]*TypeParam, len(rparams))
147 for i, rparam := range rparams {
148 rlist[i] = check.declareTypeParam(rparam)
150 sig.rparams = bindTParams(rlist)
151 // determine receiver type to get its type parameters
152 // and the respective type parameter bounds
153 var recvTParams []*TypeParam
155 // recv should be a Named type (otherwise an error is reported elsewhere)
156 // Also: Don't report an error via genericType since it will be reported
157 // again when we type-check the signature.
158 // TODO(gri) maybe the receiver should be marked as invalid instead?
159 if recv, _ := check.genericType(rname, false).(*Named); recv != nil {
160 recvTParams = recv.TypeParams().list()
163 // provide type parameter bounds
164 // - only do this if we have the right number (otherwise an error is reported elsewhere)
165 if sig.RecvTypeParams().Len() == len(recvTParams) {
166 // We have a list of *TypeNames but we need a list of Types.
167 list := make([]Type, sig.RecvTypeParams().Len())
168 for i, t := range sig.RecvTypeParams().list() {
171 smap := makeSubstMap(recvTParams, list)
172 for i, tpar := range sig.RecvTypeParams().list() {
173 bound := recvTParams[i].bound
174 // bound is (possibly) parameterized in the context of the
175 // receiver type declaration. Substitute parameters for the
177 tpar.bound = check.subst(tpar.obj.pos, bound, smap, nil)
184 check.collectTypeParams(&sig.tparams, tparams)
185 // Always type-check method type parameters but complain if they are not enabled.
186 // (A separate check is needed when type-checking interface method signatures because
187 // they don't have a receiver specification.)
188 if recvPar != nil && !acceptMethodTypeParams {
189 check.error(ftyp, "methods cannot have type parameters")
193 // Value (non-type) parameters' scope starts in the function body. Use a temporary scope for their
194 // declarations and then squash that scope into the parent scope (and report any redeclarations at
196 scope := NewScope(check.scope, nopos, nopos, "function body (temp. scope)")
197 var recvList []*Var // TODO(gri) remove the need for making a list here
199 recvList, _ = check.collectParams(scope, []*syntax.Field{recvPar}, recvTyp, false) // use rewritten receiver type, if any
201 params, variadic := check.collectParams(scope, ftyp.ParamList, nil, true)
202 results, _ := check.collectParams(scope, ftyp.ResultList, nil, false)
203 scope.Squash(func(obj, alt Object) {
205 err.errorf(obj, "%s redeclared in this block", obj.Name())
206 err.recordAltDecl(alt)
211 // recv parameter list present (may be empty)
212 // spec: "The receiver is specified via an extra parameter section preceding the
213 // method name. That parameter section must declare a single parameter, the receiver."
215 switch len(recvList) {
217 // error reported by resolver
218 recv = NewParam(nopos, nil, "", Typ[Invalid]) // ignore recv below
220 // more than one receiver
221 check.error(recvList[len(recvList)-1].Pos(), "method must have exactly one receiver")
222 fallthrough // continue with first receiver
227 // TODO(gri) We should delay rtyp expansion to when we actually need the
228 // receiver; thus all checks here should be delayed to later.
229 rtyp, _ := deref(recv.typ)
231 // spec: "The receiver type must be of the form T or *T where T is a type name."
232 // (ignore invalid types - error was reported before)
233 if rtyp != Typ[Invalid] {
235 switch T := rtyp.(type) {
237 T.resolve(check.conf.Context)
238 // The receiver type may be an instantiated type referred to
239 // by an alias (which cannot have receiver parameters for now).
240 if T.TypeArgs() != nil && sig.RecvTypeParams() == nil {
241 check.errorf(recv.pos, "cannot define methods on instantiated type %s", recv.typ)
244 // spec: "The type denoted by T is called the receiver base type; it must not
245 // be a pointer or interface type and it must be declared in the same package
247 if T.obj.pkg != check.pkg {
248 err = "type not defined in this package"
249 if check.conf.CompilerErrorMessages {
250 check.errorf(recv.pos, "cannot define new methods on non-local type %s", recv.typ)
254 // The underlying type of a receiver base type can be a type parameter;
255 // e.g. for methods with a generic receiver T[P] with type T[P any] P.
256 underIs(T, func(u Type) bool {
257 switch u := u.(type) {
259 // unsafe.Pointer is treated like a regular pointer
260 if u.kind == UnsafePointer {
261 err = "unsafe.Pointer"
264 case *Pointer, *Interface:
265 err = "pointer or interface type"
272 err = "basic or unnamed type"
273 if check.conf.CompilerErrorMessages {
274 check.errorf(recv.pos, "cannot define new methods on non-local type %s", recv.typ)
278 check.errorf(recv.pos, "invalid receiver type %s", recv.typ)
281 check.errorf(recv.pos, "invalid receiver type %s (%s)", recv.typ, err)
288 sig.params = NewTuple(params...)
289 sig.results = NewTuple(results...)
290 sig.variadic = variadic
293 // collectParams declares the parameters of list in scope and returns the corresponding
294 // variable list. If type0 != nil, it is used instead of the first type in list.
295 func (check *Checker) collectParams(scope *Scope, list []*syntax.Field, type0 syntax.Expr, variadicOk bool) (params []*Var, variadic bool) {
300 var named, anonymous bool
304 for i, field := range list {
306 // type-check type of grouped fields only once
309 if i == 0 && type0 != nil {
312 if t, _ := ftype.(*syntax.DotsType); t != nil {
314 if variadicOk && i == len(list)-1 {
317 check.softErrorf(t, "can only use ... with final parameter in list")
318 // ignore ... and continue
321 typ = check.varType(ftype)
323 // The parser ensures that f.Tag is nil and we don't
324 // care if a constructed AST contains a non-nil tag.
325 if field.Name != nil {
327 name := field.Name.Value
329 check.error(field.Name, invalidAST+"anonymous parameter")
332 par := NewParam(field.Name.Pos(), check.pkg, name, typ)
333 check.declare(scope, field.Name, par, scope.pos)
334 params = append(params, par)
337 // anonymous parameter
338 par := NewParam(field.Pos(), check.pkg, "", typ)
339 check.recordImplicit(field, par)
340 params = append(params, par)
345 if named && anonymous {
346 check.error(list[0], invalidAST+"list contains both named and anonymous parameters")
350 // For a variadic function, change the last parameter's type from T to []T.
351 // Since we type-checked T rather than ...T, we also need to retro-actively
352 // record the type for ...T.
354 last := params[len(params)-1]
355 last.typ = &Slice{elem: last.typ}
356 check.recordTypeAndValue(list[len(list)-1].Type, typexpr, last.typ, nil)
362 // isubst returns an x with identifiers substituted per the substitution map smap.
363 // isubst only handles the case of (valid) method receiver type expressions correctly.
364 func isubst(x syntax.Expr, smap map[*syntax.Name]*syntax.Name) syntax.Expr {
365 switch n := x.(type) {
367 if alt := smap[n]; alt != nil {
370 // case *syntax.StarExpr:
371 // X := isubst(n.X, smap)
377 case *syntax.Operation:
378 if n.Op == syntax.Mul && n.Y == nil {
379 X := isubst(n.X, smap)
386 case *syntax.IndexExpr:
387 Index := isubst(n.Index, smap)
388 if Index != n.Index {
393 case *syntax.ListExpr:
394 var elems []syntax.Expr
395 for i, elem := range n.ElemList {
396 new := isubst(elem, smap)
399 elems = make([]syntax.Expr, len(n.ElemList))
400 copy(elems, n.ElemList)
410 case *syntax.ParenExpr:
411 return isubst(n.X, smap) // no need to keep parentheses
413 // Other receiver type expressions are invalid.
414 // It's fine to ignore those here as they will
415 // be checked elsewhere.