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 *TParamList // receiver type parameters from left to right, or nil
23 tparams *TParamList // 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.
35 func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature {
39 panic("variadic function must have at least one parameter")
41 if _, ok := params.At(n - 1).typ.(*Slice); !ok {
42 panic("variadic parameter must be of unnamed slice type")
45 return &Signature{recv: recv, params: params, results: results, variadic: variadic}
48 // Recv returns the receiver of signature s (if a method), or nil if a
49 // function. It is ignored when comparing signatures for identity.
51 // For an abstract method, Recv returns the enclosing interface either
52 // as a *Named or an *Interface. Due to embedding, an interface may
53 // contain methods whose receiver type is a different interface.
54 func (s *Signature) Recv() *Var { return s.recv }
56 // TParams returns the type parameters of signature s, or nil.
57 func (s *Signature) TParams() *TParamList { return s.tparams }
59 // SetTParams sets the type parameters of signature s.
60 func (s *Signature) SetTParams(tparams []*TypeParam) { s.tparams = bindTParams(tparams) }
62 // RParams returns the receiver type parameters of signature s, or nil.
63 func (s *Signature) RParams() *TParamList { return s.rparams }
65 // SetRParams sets the receiver type params of signature s.
66 func (s *Signature) SetRParams(rparams []*TypeParam) { s.rparams = bindTParams(rparams) }
68 // Params returns the parameters of signature s, or nil.
69 func (s *Signature) Params() *Tuple { return s.params }
71 // Results returns the results of signature s, or nil.
72 func (s *Signature) Results() *Tuple { return s.results }
74 // Variadic reports whether the signature s is variadic.
75 func (s *Signature) Variadic() bool { return s.variadic }
77 func (s *Signature) Underlying() Type { return s }
78 func (s *Signature) String() string { return TypeString(s, nil) }
80 // ----------------------------------------------------------------------------
83 // Disabled by default, but enabled when running tests (via types_test.go).
84 var acceptMethodTypeParams bool
86 // funcType type-checks a function or method type.
87 func (check *Checker) funcType(sig *Signature, recvPar *syntax.Field, tparams []*syntax.Field, ftyp *syntax.FuncType) {
88 check.openScope(ftyp, "function")
89 check.scope.isFunc = true
90 check.recordScope(ftyp, check.scope)
91 sig.scope = check.scope
92 defer check.closeScope()
94 var recvTyp syntax.Expr // rewritten receiver type; valid if != nil
96 // collect generic receiver type parameters, if any
97 // - a receiver type parameter is like any other type parameter, except that it is declared implicitly
98 // - the receiver specification acts as local declaration for its type parameters, which may be blank
99 _, rname, rparams := check.unpackRecv(recvPar.Type, true)
100 if len(rparams) > 0 {
101 // Blank identifiers don't get declared and regular type-checking of the instantiated
102 // parameterized receiver type expression fails in Checker.collectParams of receiver.
103 // Identify blank type parameters and substitute each with a unique new identifier named
104 // "n_" (where n is the parameter index) and which cannot conflict with any user-defined
106 var smap map[*syntax.Name]*syntax.Name // substitution map from "_" to "!n" identifiers
107 for i, p := range rparams {
110 new.Value = fmt.Sprintf("%d_", i)
111 rparams[i] = &new // use n_ identifier instead of _ so it can be looked up
113 smap = make(map[*syntax.Name]*syntax.Name)
119 // blank identifiers were found => use rewritten receiver type
120 recvTyp = isubst(recvPar.Type, smap)
122 rlist := make([]*TypeParam, len(rparams))
123 for i, rparam := range rparams {
124 rlist[i] = check.declareTypeParam(rparam)
126 sig.rparams = bindTParams(rlist)
127 // determine receiver type to get its type parameters
128 // and the respective type parameter bounds
129 var recvTParams []*TypeParam
131 // recv should be a Named type (otherwise an error is reported elsewhere)
132 // Also: Don't report an error via genericType since it will be reported
133 // again when we type-check the signature.
134 // TODO(gri) maybe the receiver should be marked as invalid instead?
135 if recv := asNamed(check.genericType(rname, false)); recv != nil {
136 recvTParams = recv.TParams().list()
139 // provide type parameter bounds
140 // - only do this if we have the right number (otherwise an error is reported elsewhere)
141 if sig.RParams().Len() == len(recvTParams) {
142 // We have a list of *TypeNames but we need a list of Types.
143 list := make([]Type, sig.RParams().Len())
144 for i, t := range sig.RParams().list() {
147 smap := makeSubstMap(recvTParams, list)
148 for i, tpar := range sig.RParams().list() {
149 bound := recvTParams[i].bound
150 // bound is (possibly) parameterized in the context of the
151 // receiver type declaration. Substitute parameters for the
153 tpar.bound = check.subst(tpar.obj.pos, bound, smap, nil)
160 sig.tparams = check.collectTypeParams(tparams)
161 // Always type-check method type parameters but complain if they are not enabled.
162 // (A separate check is needed when type-checking interface method signatures because
163 // they don't have a receiver specification.)
164 if recvPar != nil && !acceptMethodTypeParams {
165 check.error(ftyp, "methods cannot have type parameters")
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}, recvTyp, false) // use rewritten receiver type, if any
177 params, variadic := check.collectParams(scope, ftyp.ParamList, nil, true)
178 results, _ := check.collectParams(scope, ftyp.ResultList, nil, 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(), "method must have exactly one receiver")
198 fallthrough // continue with first receiver
203 // TODO(gri) We should delay rtyp expansion to when we actually need the
204 // receiver; thus all checks here should be delayed to later.
205 rtyp, _ := deref(recv.typ)
207 // spec: "The receiver type must be of the form T or *T where T is a type name."
208 // (ignore invalid types - error was reported before)
209 if rtyp != Typ[Invalid] {
211 switch T := rtyp.(type) {
214 // spec: "The type denoted by T is called the receiver base type; it must not
215 // be a pointer or interface type and it must be declared in the same package
217 if T.obj.pkg != check.pkg {
218 err = "type not defined in this package"
219 if check.conf.CompilerErrorMessages {
220 check.errorf(recv.pos, "cannot define new methods on non-local type %s", recv.typ)
224 // The underlying type of a receiver base type can be a type parameter;
225 // e.g. for methods with a generic receiver T[P] with type T[P any] P.
226 underIs(T, func(u Type) bool {
227 switch u := u.(type) {
229 // unsafe.Pointer is treated like a regular pointer
230 if u.kind == UnsafePointer {
231 err = "unsafe.Pointer"
234 case *Pointer, *Interface:
235 err = "pointer or interface type"
242 err = "basic or unnamed type"
243 if check.conf.CompilerErrorMessages {
244 check.errorf(recv.pos, "cannot define new methods on non-local type %s", recv.typ)
248 check.errorf(recv.pos, "invalid receiver type %s", recv.typ)
251 check.errorf(recv.pos, "invalid receiver type %s (%s)", recv.typ, err)
258 sig.params = NewTuple(params...)
259 sig.results = NewTuple(results...)
260 sig.variadic = variadic
263 // collectParams declares the parameters of list in scope and returns the corresponding
264 // variable list. If type0 != nil, it is used instead of the first type in list.
265 func (check *Checker) collectParams(scope *Scope, list []*syntax.Field, type0 syntax.Expr, variadicOk bool) (params []*Var, variadic bool) {
270 var named, anonymous bool
274 for i, field := range list {
276 // type-check type of grouped fields only once
279 if i == 0 && type0 != nil {
282 if t, _ := ftype.(*syntax.DotsType); t != nil {
284 if variadicOk && i == len(list)-1 {
287 check.softErrorf(t, "can only use ... with final parameter in list")
288 // ignore ... and continue
291 typ = check.varType(ftype)
293 // The parser ensures that f.Tag is nil and we don't
294 // care if a constructed AST contains a non-nil tag.
295 if field.Name != nil {
297 name := field.Name.Value
299 check.error(field.Name, invalidAST+"anonymous parameter")
302 par := NewParam(field.Name.Pos(), check.pkg, name, typ)
303 check.declare(scope, field.Name, par, scope.pos)
304 params = append(params, par)
307 // anonymous parameter
308 par := NewParam(field.Pos(), check.pkg, "", typ)
309 check.recordImplicit(field, par)
310 params = append(params, par)
315 if named && anonymous {
316 check.error(list[0], invalidAST+"list contains both named and anonymous parameters")
320 // For a variadic function, change the last parameter's type from T to []T.
321 // Since we type-checked T rather than ...T, we also need to retro-actively
322 // record the type for ...T.
324 last := params[len(params)-1]
325 last.typ = &Slice{elem: last.typ}
326 check.recordTypeAndValue(list[len(list)-1].Type, typexpr, last.typ, nil)
332 // isubst returns an x with identifiers substituted per the substitution map smap.
333 // isubst only handles the case of (valid) method receiver type expressions correctly.
334 func isubst(x syntax.Expr, smap map[*syntax.Name]*syntax.Name) syntax.Expr {
335 switch n := x.(type) {
337 if alt := smap[n]; alt != nil {
340 // case *syntax.StarExpr:
341 // X := isubst(n.X, smap)
347 case *syntax.Operation:
348 if n.Op == syntax.Mul && n.Y == nil {
349 X := isubst(n.X, smap)
356 case *syntax.IndexExpr:
357 Index := isubst(n.Index, smap)
358 if Index != n.Index {
363 case *syntax.ListExpr:
364 var elems []syntax.Expr
365 for i, elem := range n.ElemList {
366 new := isubst(elem, smap)
369 elems = make([]syntax.Expr, len(n.ElemList))
370 copy(elems, n.ElemList)
380 case *syntax.ParenExpr:
381 return isubst(n.X, smap) // no need to keep parentheses
383 // Other receiver type expressions are invalid.
384 // It's fine to ignore those here as they will
385 // be checked elsewhere.