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. 4 5package types 6 7import ( 8 "fmt" 9 "go/ast" 10 "go/token" 11 . "internal/types/errors" 12) 13 14// ---------------------------------------------------------------------------- 15// API 16 17// A Signature represents a (non-builtin) function or method type. 18// The receiver is ignored when comparing signatures for identity. 19type Signature struct { 20 // We need to keep the scope in Signature (rather than passing it around 21 // and store it in the Func Object) because when type-checking a function 22 // literal we call the general type checker which returns a general Type. 23 // We then unpack the *Signature and use the scope for the literal body. 24 rparams *TypeParamList // receiver type parameters from left to right, or nil 25 tparams *TypeParamList // type parameters from left to right, or nil 26 scope *Scope // function scope for package-local and non-instantiated signatures; nil otherwise 27 recv *Var // nil if not a method 28 params *Tuple // (incoming) parameters from left to right; or nil 29 results *Tuple // (outgoing) results from left to right; or nil 30 variadic bool // true if the last parameter's type is of the form ...T (or string, for append built-in only) 31} 32 33// NewSignature returns a new function type for the given receiver, parameters, 34// and results, either of which may be nil. If variadic is set, the function 35// is variadic, it must have at least one parameter, and the last parameter 36// must be of unnamed slice type. 37// 38// Deprecated: Use [NewSignatureType] instead which allows for type parameters. 39func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature { 40 return NewSignatureType(recv, nil, nil, params, results, variadic) 41} 42 43// NewSignatureType creates a new function type for the given receiver, 44// receiver type parameters, type parameters, parameters, and results. If 45// variadic is set, params must hold at least one parameter and the last 46// parameter's core type must be of unnamed slice or bytestring type. 47// If recv is non-nil, typeParams must be empty. If recvTypeParams is 48// non-empty, recv must be non-nil. 49func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature { 50 if variadic { 51 n := params.Len() 52 if n == 0 { 53 panic("variadic function must have at least one parameter") 54 } 55 core := coreString(params.At(n - 1).typ) 56 if _, ok := core.(*Slice); !ok && !isString(core) { 57 panic(fmt.Sprintf("got %s, want variadic parameter with unnamed slice type or string as core type", core.String())) 58 } 59 } 60 sig := &Signature{recv: recv, params: params, results: results, variadic: variadic} 61 if len(recvTypeParams) != 0 { 62 if recv == nil { 63 panic("function with receiver type parameters must have a receiver") 64 } 65 sig.rparams = bindTParams(recvTypeParams) 66 } 67 if len(typeParams) != 0 { 68 if recv != nil { 69 panic("function with type parameters cannot have a receiver") 70 } 71 sig.tparams = bindTParams(typeParams) 72 } 73 return sig 74} 75 76// Recv returns the receiver of signature s (if a method), or nil if a 77// function. It is ignored when comparing signatures for identity. 78// 79// For an abstract method, Recv returns the enclosing interface either 80// as a *[Named] or an *[Interface]. Due to embedding, an interface may 81// contain methods whose receiver type is a different interface. 82func (s *Signature) Recv() *Var { return s.recv } 83 84// TypeParams returns the type parameters of signature s, or nil. 85func (s *Signature) TypeParams() *TypeParamList { return s.tparams } 86 87// RecvTypeParams returns the receiver type parameters of signature s, or nil. 88func (s *Signature) RecvTypeParams() *TypeParamList { return s.rparams } 89 90// Params returns the parameters of signature s, or nil. 91func (s *Signature) Params() *Tuple { return s.params } 92 93// Results returns the results of signature s, or nil. 94func (s *Signature) Results() *Tuple { return s.results } 95 96// Variadic reports whether the signature s is variadic. 97func (s *Signature) Variadic() bool { return s.variadic } 98 99func (t *Signature) Underlying() Type { return t } 100func (t *Signature) String() string { return TypeString(t, nil) } 101 102// ---------------------------------------------------------------------------- 103// Implementation 104 105// funcType type-checks a function or method type. 106func (check *Checker) funcType(sig *Signature, recvPar *ast.FieldList, ftyp *ast.FuncType) { 107 check.openScope(ftyp, "function") 108 check.scope.isFunc = true 109 check.recordScope(ftyp, check.scope) 110 sig.scope = check.scope 111 defer check.closeScope() 112 113 if recvPar != nil && len(recvPar.List) > 0 { 114 // collect generic receiver type parameters, if any 115 // - a receiver type parameter is like any other type parameter, except that it is declared implicitly 116 // - the receiver specification acts as local declaration for its type parameters, which may be blank 117 _, rname, rparams := check.unpackRecv(recvPar.List[0].Type, true) 118 if len(rparams) > 0 { 119 // The scope of the type parameter T in "func (r T[T]) f()" 120 // starts after f, not at "r"; see #52038. 121 scopePos := ftyp.Params.Pos() 122 tparams := check.declareTypeParams(nil, rparams, scopePos) 123 sig.rparams = bindTParams(tparams) 124 // Blank identifiers don't get declared, so naive type-checking of the 125 // receiver type expression would fail in Checker.collectParams below, 126 // when Checker.ident cannot resolve the _ to a type. 127 // 128 // Checker.recvTParamMap maps these blank identifiers to their type parameter 129 // types, so that they may be resolved in Checker.ident when they fail 130 // lookup in the scope. 131 for i, p := range rparams { 132 if p.Name == "_" { 133 if check.recvTParamMap == nil { 134 check.recvTParamMap = make(map[*ast.Ident]*TypeParam) 135 } 136 check.recvTParamMap[p] = tparams[i] 137 } 138 } 139 // determine receiver type to get its type parameters 140 // and the respective type parameter bounds 141 var recvTParams []*TypeParam 142 if rname != nil { 143 // recv should be a Named type (otherwise an error is reported elsewhere) 144 // Also: Don't report an error via genericType since it will be reported 145 // again when we type-check the signature. 146 // TODO(gri) maybe the receiver should be marked as invalid instead? 147 if recv := asNamed(check.genericType(rname, nil)); recv != nil { 148 recvTParams = recv.TypeParams().list() 149 } 150 } 151 // provide type parameter bounds 152 if len(tparams) == len(recvTParams) { 153 smap := makeRenameMap(recvTParams, tparams) 154 for i, tpar := range tparams { 155 recvTPar := recvTParams[i] 156 check.mono.recordCanon(tpar, recvTPar) 157 // recvTPar.bound is (possibly) parameterized in the context of the 158 // receiver type declaration. Substitute parameters for the current 159 // context. 160 tpar.bound = check.subst(tpar.obj.pos, recvTPar.bound, smap, nil, check.context()) 161 } 162 } else if len(tparams) < len(recvTParams) { 163 // Reporting an error here is a stop-gap measure to avoid crashes in the 164 // compiler when a type parameter/argument cannot be inferred later. It 165 // may lead to follow-on errors (see issues go.dev/issue/51339, go.dev/issue/51343). 166 // TODO(gri) find a better solution 167 got := measure(len(tparams), "type parameter") 168 check.errorf(recvPar, BadRecv, "got %s, but receiver base type declares %d", got, len(recvTParams)) 169 } 170 } 171 } 172 173 if ftyp.TypeParams != nil { 174 check.collectTypeParams(&sig.tparams, ftyp.TypeParams) 175 // Always type-check method type parameters but complain that they are not allowed. 176 // (A separate check is needed when type-checking interface method signatures because 177 // they don't have a receiver specification.) 178 if recvPar != nil { 179 check.error(ftyp.TypeParams, InvalidMethodTypeParams, "methods cannot have type parameters") 180 } 181 } 182 183 // Use a temporary scope for all parameter declarations and then 184 // squash that scope into the parent scope (and report any 185 // redeclarations at that time). 186 // 187 // TODO(adonovan): now that each declaration has the correct 188 // scopePos, there should be no need for scope squashing. 189 // Audit to ensure all lookups honor scopePos and simplify. 190 scope := NewScope(check.scope, nopos, nopos, "function body (temp. scope)") 191 scopePos := ftyp.End() // all parameters' scopes start after the signature 192 recvList, _ := check.collectParams(scope, recvPar, false, scopePos) 193 params, variadic := check.collectParams(scope, ftyp.Params, true, scopePos) 194 results, _ := check.collectParams(scope, ftyp.Results, false, scopePos) 195 scope.squash(func(obj, alt Object) { 196 err := check.newError(DuplicateDecl) 197 err.addf(obj, "%s redeclared in this block", obj.Name()) 198 err.addAltDecl(alt) 199 err.report() 200 }) 201 202 if recvPar != nil { 203 // recv parameter list present (may be empty) 204 // spec: "The receiver is specified via an extra parameter section preceding the 205 // method name. That parameter section must declare a single parameter, the receiver." 206 var recv *Var 207 switch len(recvList) { 208 case 0: 209 // error reported by resolver 210 recv = NewParam(nopos, nil, "", Typ[Invalid]) // ignore recv below 211 default: 212 // more than one receiver 213 check.error(recvList[len(recvList)-1], InvalidRecv, "method has multiple receivers") 214 fallthrough // continue with first receiver 215 case 1: 216 recv = recvList[0] 217 } 218 sig.recv = recv 219 220 // Delay validation of receiver type as it may cause premature expansion 221 // of types the receiver type is dependent on (see issues go.dev/issue/51232, go.dev/issue/51233). 222 check.later(func() { 223 // spec: "The receiver type must be of the form T or *T where T is a type name." 224 rtyp, _ := deref(recv.typ) 225 atyp := Unalias(rtyp) 226 if !isValid(atyp) { 227 return // error was reported before 228 } 229 // spec: "The type denoted by T is called the receiver base type; it must not 230 // be a pointer or interface type and it must be declared in the same package 231 // as the method." 232 switch T := atyp.(type) { 233 case *Named: 234 // The receiver type may be an instantiated type referred to 235 // by an alias (which cannot have receiver parameters for now). 236 if T.TypeArgs() != nil && sig.RecvTypeParams() == nil { 237 check.errorf(recv, InvalidRecv, "cannot define new methods on instantiated type %s", rtyp) 238 break 239 } 240 if T.obj.pkg != check.pkg { 241 check.errorf(recv, InvalidRecv, "cannot define new methods on non-local type %s", rtyp) 242 break 243 } 244 var cause string 245 switch u := T.under().(type) { 246 case *Basic: 247 // unsafe.Pointer is treated like a regular pointer 248 if u.kind == UnsafePointer { 249 cause = "unsafe.Pointer" 250 } 251 case *Pointer, *Interface: 252 cause = "pointer or interface type" 253 case *TypeParam: 254 // The underlying type of a receiver base type cannot be a 255 // type parameter: "type T[P any] P" is not a valid declaration. 256 panic("unreachable") 257 } 258 if cause != "" { 259 check.errorf(recv, InvalidRecv, "invalid receiver type %s (%s)", rtyp, cause) 260 } 261 case *Basic: 262 check.errorf(recv, InvalidRecv, "cannot define new methods on non-local type %s", rtyp) 263 default: 264 check.errorf(recv, InvalidRecv, "invalid receiver type %s", recv.typ) 265 } 266 }).describef(recv, "validate receiver %s", recv) 267 } 268 269 sig.params = NewTuple(params...) 270 sig.results = NewTuple(results...) 271 sig.variadic = variadic 272} 273 274// collectParams declares the parameters of list in scope and returns the corresponding 275// variable list. 276func (check *Checker) collectParams(scope *Scope, list *ast.FieldList, variadicOk bool, scopePos token.Pos) (params []*Var, variadic bool) { 277 if list == nil { 278 return 279 } 280 281 var named, anonymous bool 282 for i, field := range list.List { 283 ftype := field.Type 284 if t, _ := ftype.(*ast.Ellipsis); t != nil { 285 ftype = t.Elt 286 if variadicOk && i == len(list.List)-1 && len(field.Names) <= 1 { 287 variadic = true 288 } else { 289 check.softErrorf(t, MisplacedDotDotDot, "can only use ... with final parameter in list") 290 // ignore ... and continue 291 } 292 } 293 typ := check.varType(ftype) 294 // The parser ensures that f.Tag is nil and we don't 295 // care if a constructed AST contains a non-nil tag. 296 if len(field.Names) > 0 { 297 // named parameter 298 for _, name := range field.Names { 299 if name.Name == "" { 300 check.error(name, InvalidSyntaxTree, "anonymous parameter") 301 // ok to continue 302 } 303 par := NewParam(name.Pos(), check.pkg, name.Name, typ) 304 check.declare(scope, name, par, scopePos) 305 params = append(params, par) 306 } 307 named = true 308 } else { 309 // anonymous parameter 310 par := NewParam(ftype.Pos(), check.pkg, "", typ) 311 check.recordImplicit(field, par) 312 params = append(params, par) 313 anonymous = true 314 } 315 } 316 317 if named && anonymous { 318 check.error(list, InvalidSyntaxTree, "list contains both named and anonymous parameters") 319 // ok to continue 320 } 321 322 // For a variadic function, change the last parameter's type from T to []T. 323 // Since we type-checked T rather than ...T, we also need to retro-actively 324 // record the type for ...T. 325 if variadic { 326 last := params[len(params)-1] 327 last.typ = &Slice{elem: last.typ} 328 check.recordTypeAndValue(list.List[len(list.List)-1].Type, typexpr, last.typ, nil) 329 } 330 331 return 332} 333