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 // Disabled by default, but enabled when running tests (via types_test.go).
13 var acceptMethodTypeParams bool
15 // funcType type-checks a function or method type.
16 func (check *Checker) funcType(sig *Signature, recvPar *syntax.Field, tparams []*syntax.Field, ftyp *syntax.FuncType) {
17 check.openScope(ftyp, "function")
18 check.scope.isFunc = true
19 check.recordScope(ftyp, check.scope)
20 sig.scope = check.scope
21 defer check.closeScope()
23 var recvTyp syntax.Expr // rewritten receiver type; valid if != nil
25 // collect generic receiver type parameters, if any
26 // - a receiver type parameter is like any other type parameter, except that it is declared implicitly
27 // - the receiver specification acts as local declaration for its type parameters, which may be blank
28 _, rname, rparams := check.unpackRecv(recvPar.Type, true)
30 // Blank identifiers don't get declared and regular type-checking of the instantiated
31 // parameterized receiver type expression fails in Checker.collectParams of receiver.
32 // Identify blank type parameters and substitute each with a unique new identifier named
33 // "n_" (where n is the parameter index) and which cannot conflict with any user-defined
35 var smap map[*syntax.Name]*syntax.Name // substitution map from "_" to "!n" identifiers
36 for i, p := range rparams {
39 new.Value = fmt.Sprintf("%d_", i)
40 rparams[i] = &new // use n_ identifier instead of _ so it can be looked up
42 smap = make(map[*syntax.Name]*syntax.Name)
48 // blank identifiers were found => use rewritten receiver type
49 recvTyp = isubst(recvPar.Type, smap)
51 sig.rparams = make([]*TypeName, len(rparams))
52 for i, rparam := range rparams {
53 sig.rparams[i] = check.declareTypeParam(i, rparam)
55 // determine receiver type to get its type parameters
56 // and the respective type parameter bounds
57 var recvTParams []*TypeName
59 // recv should be a Named type (otherwise an error is reported elsewhere)
60 // Also: Don't report an error via genericType since it will be reported
61 // again when we type-check the signature.
62 // TODO(gri) maybe the receiver should be marked as invalid instead?
63 if recv := asNamed(check.genericType(rname, false)); recv != nil {
64 recvTParams = recv.TParams()
67 // provide type parameter bounds
68 // - only do this if we have the right number (otherwise an error is reported elsewhere)
69 if len(sig.rparams) == len(recvTParams) {
70 // We have a list of *TypeNames but we need a list of Types.
71 list := make([]Type, len(sig.rparams))
72 for i, t := range sig.rparams {
75 smap := makeSubstMap(recvTParams, list)
76 for i, tname := range sig.rparams {
77 bound := recvTParams[i].typ.(*TypeParam).bound
78 // bound is (possibly) parameterized in the context of the
79 // receiver type declaration. Substitute parameters for the
81 // TODO(gri) should we assume now that bounds always exist?
82 // (no bound == empty interface)
84 bound = check.subst(tname.pos, bound, smap)
85 tname.typ.(*TypeParam).bound = bound
93 sig.tparams = check.collectTypeParams(tparams)
94 // Always type-check method type parameters but complain if they are not enabled.
95 // (A separate check is needed when type-checking interface method signatures because
96 // they don't have a receiver specification.)
97 if recvPar != nil && !acceptMethodTypeParams {
98 check.error(ftyp, "methods cannot have type parameters")
102 // Value (non-type) parameters' scope starts in the function body. Use a temporary scope for their
103 // declarations and then squash that scope into the parent scope (and report any redeclarations at
105 scope := NewScope(check.scope, nopos, nopos, "function body (temp. scope)")
106 var recvList []*Var // TODO(gri) remove the need for making a list here
108 recvList, _ = check.collectParams(scope, []*syntax.Field{recvPar}, recvTyp, false) // use rewritten receiver type, if any
110 params, variadic := check.collectParams(scope, ftyp.ParamList, nil, true)
111 results, _ := check.collectParams(scope, ftyp.ResultList, nil, false)
112 scope.Squash(func(obj, alt Object) {
114 err.errorf(obj, "%s redeclared in this block", obj.Name())
115 err.recordAltDecl(alt)
120 // recv parameter list present (may be empty)
121 // spec: "The receiver is specified via an extra parameter section preceding the
122 // method name. That parameter section must declare a single parameter, the receiver."
124 switch len(recvList) {
126 // error reported by resolver
127 recv = NewParam(nopos, nil, "", Typ[Invalid]) // ignore recv below
129 // more than one receiver
130 check.error(recvList[len(recvList)-1].Pos(), "method must have exactly one receiver")
131 fallthrough // continue with first receiver
136 // TODO(gri) We should delay rtyp expansion to when we actually need the
137 // receiver; thus all checks here should be delayed to later.
138 rtyp, _ := deref(recv.typ)
141 // spec: "The receiver type must be of the form T or *T where T is a type name."
142 // (ignore invalid types - error was reported before)
143 if t := rtyp; t != Typ[Invalid] {
145 if T := asNamed(t); T != nil {
146 // spec: "The type denoted by T is called the receiver base type; it must not
147 // be a pointer or interface type and it must be declared in the same package
149 if T.obj.pkg != check.pkg {
150 err = "type not defined in this package"
151 if check.conf.CompilerErrorMessages {
152 check.errorf(recv.pos, "cannot define new methods on non-local type %s", recv.typ)
156 switch u := optype(T).(type) {
158 // unsafe.Pointer is treated like a regular pointer
159 if u.kind == UnsafePointer {
160 err = "unsafe.Pointer"
162 case *Pointer, *Interface:
163 err = "pointer or interface type"
166 } else if T := asBasic(t); T != nil {
167 err = "basic or unnamed type"
168 if check.conf.CompilerErrorMessages {
169 check.errorf(recv.pos, "cannot define new methods on non-local type %s", recv.typ)
173 check.errorf(recv.pos, "invalid receiver type %s", recv.typ)
176 check.errorf(recv.pos, "invalid receiver type %s (%s)", recv.typ, err)
183 sig.params = NewTuple(params...)
184 sig.results = NewTuple(results...)
185 sig.variadic = variadic
188 // collectParams declares the parameters of list in scope and returns the corresponding
189 // variable list. If type0 != nil, it is used instead of the first type in list.
190 func (check *Checker) collectParams(scope *Scope, list []*syntax.Field, type0 syntax.Expr, variadicOk bool) (params []*Var, variadic bool) {
195 var named, anonymous bool
199 for i, field := range list {
201 // type-check type of grouped fields only once
204 if i == 0 && type0 != nil {
207 if t, _ := ftype.(*syntax.DotsType); t != nil {
209 if variadicOk && i == len(list)-1 {
212 check.softErrorf(t, "can only use ... with final parameter in list")
213 // ignore ... and continue
216 typ = check.varType(ftype)
218 // The parser ensures that f.Tag is nil and we don't
219 // care if a constructed AST contains a non-nil tag.
220 if field.Name != nil {
222 name := field.Name.Value
224 check.error(field.Name, invalidAST+"anonymous parameter")
227 par := NewParam(field.Name.Pos(), check.pkg, name, typ)
228 check.declare(scope, field.Name, par, scope.pos)
229 params = append(params, par)
232 // anonymous parameter
233 par := NewParam(field.Pos(), check.pkg, "", typ)
234 check.recordImplicit(field, par)
235 params = append(params, par)
240 if named && anonymous {
241 check.error(list[0], invalidAST+"list contains both named and anonymous parameters")
245 // For a variadic function, change the last parameter's type from T to []T.
246 // Since we type-checked T rather than ...T, we also need to retro-actively
247 // record the type for ...T.
249 last := params[len(params)-1]
250 last.typ = &Slice{elem: last.typ}
251 check.recordTypeAndValue(list[len(list)-1].Type, typexpr, last.typ, nil)
257 // isubst returns an x with identifiers substituted per the substitution map smap.
258 // isubst only handles the case of (valid) method receiver type expressions correctly.
259 func isubst(x syntax.Expr, smap map[*syntax.Name]*syntax.Name) syntax.Expr {
260 switch n := x.(type) {
262 if alt := smap[n]; alt != nil {
265 // case *syntax.StarExpr:
266 // X := isubst(n.X, smap)
272 case *syntax.Operation:
273 if n.Op == syntax.Mul && n.Y == nil {
274 X := isubst(n.X, smap)
281 case *syntax.IndexExpr:
282 Index := isubst(n.Index, smap)
283 if Index != n.Index {
288 case *syntax.ListExpr:
289 var elems []syntax.Expr
290 for i, elem := range n.ElemList {
291 new := isubst(elem, smap)
294 elems = make([]syntax.Expr, len(n.ElemList))
295 copy(elems, n.ElemList)
305 case *syntax.ParenExpr:
306 return isubst(n.X, smap) // no need to keep parentheses
308 // Other receiver type expressions are invalid.
309 // It's fine to ignore those here as they will
310 // be checked elsewhere.