| 1 |
// Copyright 2013 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 |
|
| 5 |
// This file implements typechecking of call and selector expressions. |
| 6 |
|
| 7 |
package types2 |
| 8 |
|
| 9 |
import ( |
| 10 |
"cmd/compile/internal/syntax" |
| 11 |
. "internal/types/errors" |
| 12 |
"strings" |
| 13 |
) |
| 14 |
|
| 15 |
// funcInst type-checks a function instantiation. |
| 16 |
// The incoming x must be a generic function. |
| 17 |
// If inst != nil, it provides some or all of the type arguments (inst.Index). |
| 18 |
// If target != nil, it may be used to infer missing type arguments of x, if any. |
| 19 |
// At least one of T or inst must be provided. |
| 20 |
// |
| 21 |
// There are two modes of operation: |
| 22 |
// |
| 23 |
// 1. If infer == true, funcInst infers missing type arguments as needed and |
| 24 |
// instantiates the function x. The returned results are nil. |
| 25 |
// |
| 26 |
// 2. If infer == false and inst provides all type arguments, funcInst |
| 27 |
// instantiates the function x. The returned results are nil. |
| 28 |
// If inst doesn't provide enough type arguments, funcInst returns the |
| 29 |
// available arguments; x remains unchanged. |
| 30 |
// |
| 31 |
// If an error (other than a version error) occurs in any case, it is reported |
| 32 |
// and x.mode is set to invalid. |
| 33 |
func (check *Checker) funcInst(T *target, pos syntax.Pos, x *operand, inst *syntax.IndexExpr, infer bool) []Type { |
| 34 |
assert(T != nil || inst != nil) |
| 35 |
|
| 36 |
var instErrPos poser |
| 37 |
if inst != nil { |
| 38 |
instErrPos = inst.Pos() |
| 39 |
x.expr = inst // if we don't have an index expression, keep the existing expression of x |
| 40 |
} else { |
| 41 |
instErrPos = pos |
| 42 |
} |
| 43 |
versionErr := !check.verifyVersionf(instErrPos, go1_18, "function instantiation") |
| 44 |
|
| 45 |
// targs and xlist are the type arguments and corresponding type expressions, or nil. |
| 46 |
var targs []Type |
| 47 |
var xlist []syntax.Expr |
| 48 |
if inst != nil { |
| 49 |
xlist = syntax.UnpackListExpr(inst.Index) |
| 50 |
targs = check.typeList(xlist) |
| 51 |
if targs == nil { |
| 52 |
x.mode = invalid |
| 53 |
return nil |
| 54 |
} |
| 55 |
assert(len(targs) == len(xlist)) |
| 56 |
} |
| 57 |
|
| 58 |
// Check the number of type arguments (got) vs number of type parameters (want). |
| 59 |
// Note that x is a function value, not a type expression, so we don't need to |
| 60 |
// call Underlying below. |
| 61 |
sig := x.typ.(*Signature) |
| 62 |
got, want := len(targs), sig.TypeParams().Len() |
| 63 |
if got > want { |
| 64 |
// Providing too many type arguments is always an error. |
| 65 |
check.errorf(xlist[got-1], WrongTypeArgCount, "got %d type arguments but want %d", got, want) |
| 66 |
x.mode = invalid |
| 67 |
return nil |
| 68 |
} |
| 69 |
|
| 70 |
if got < want { |
| 71 |
if !infer { |
| 72 |
return targs |
| 73 |
} |
| 74 |
|
| 75 |
// If the uninstantiated or partially instantiated function x is used in |
| 76 |
// an assignment (tsig != nil), infer missing type arguments by treating |
| 77 |
// the assignment |
| 78 |
// |
| 79 |
// var tvar tsig = x |
| 80 |
// |
| 81 |
// like a call g(tvar) of the synthetic generic function g |
| 82 |
// |
| 83 |
// func g[type_parameters_of_x](func_type_of_x) |
| 84 |
// |
| 85 |
var args []*operand |
| 86 |
var params []*Var |
| 87 |
var reverse bool |
| 88 |
if T != nil && sig.tparams != nil { |
| 89 |
if !versionErr && !check.allowVersion(go1_21) { |
| 90 |
if inst != nil { |
| 91 |
check.versionErrorf(instErrPos, go1_21, "partially instantiated function in assignment") |
| 92 |
} else { |
| 93 |
check.versionErrorf(instErrPos, go1_21, "implicitly instantiated function in assignment") |
| 94 |
} |
| 95 |
} |
| 96 |
gsig := NewSignatureType(nil, nil, nil, sig.params, sig.results, sig.variadic) |
| 97 |
params = []*Var{NewParam(x.Pos(), check.pkg, "", gsig)} |
| 98 |
// The type of the argument operand is tsig, which is the type of the LHS in an assignment |
| 99 |
// or the result type in a return statement. Create a pseudo-expression for that operand |
| 100 |
// that makes sense when reported in error messages from infer, below. |
| 101 |
expr := syntax.NewName(x.Pos(), T.desc) |
| 102 |
args = []*operand{{mode: value, expr: expr, typ: T.sig}} |
| 103 |
reverse = true |
| 104 |
} |
| 105 |
|
| 106 |
// Rename type parameters to avoid problems with recursive instantiations. |
| 107 |
// Note that NewTuple(params...) below is (*Tuple)(nil) if len(params) == 0, as desired. |
| 108 |
tparams, params2 := check.renameTParams(pos, sig.TypeParams().list(), NewTuple(params...)) |
| 109 |
|
| 110 |
err := check.newError(CannotInferTypeArgs) |
| 111 |
targs = check.infer(pos, tparams, targs, params2.(*Tuple), args, reverse, err) |
| 112 |
if targs == nil { |
| 113 |
if !err.empty() { |
| 114 |
err.report() |
| 115 |
} |
| 116 |
x.mode = invalid |
| 117 |
return nil |
| 118 |
} |
| 119 |
got = len(targs) |
| 120 |
} |
| 121 |
assert(got == want) |
| 122 |
|
| 123 |
// instantiate function signature |
| 124 |
sig = check.instantiateSignature(x.Pos(), x.expr, sig, targs, xlist) |
| 125 |
|
| 126 |
x.typ = sig |
| 127 |
x.mode = value |
| 128 |
return nil |
| 129 |
} |
| 130 |
|
| 131 |
func (check *Checker) instantiateSignature(pos syntax.Pos, expr syntax.Expr, typ *Signature, targs []Type, xlist []syntax.Expr) (res *Signature) { |
| 132 |
assert(check != nil) |
| 133 |
assert(len(targs) == typ.TypeParams().Len()) |
| 134 |
|
| 135 |
if check.conf.Trace { |
| 136 |
check.trace(pos, "-- instantiating signature %s with %s", typ, targs) |
| 137 |
check.indent++ |
| 138 |
defer func() { |
| 139 |
check.indent-- |
| 140 |
check.trace(pos, "=> %s (under = %s)", res, res.Underlying()) |
| 141 |
}() |
| 142 |
} |
| 143 |
|
| 144 |
// For signatures, Checker.instance will always succeed because the type argument |
| 145 |
// count is correct at this point (see assertion above); hence the type assertion |
| 146 |
// to *Signature will always succeed. |
| 147 |
inst := check.instance(pos, typ, targs, nil, check.context()).(*Signature) |
| 148 |
assert(inst.TypeParams().Len() == 0) // signature is not generic anymore |
| 149 |
check.recordInstance(expr, targs, inst) |
| 150 |
assert(len(xlist) <= len(targs)) |
| 151 |
|
| 152 |
// verify instantiation lazily (was go.dev/issue/50450) |
| 153 |
check.later(func() { |
| 154 |
tparams := typ.TypeParams().list() |
| 155 |
// check type constraints |
| 156 |
if i, err := check.verify(pos, tparams, targs, check.context()); err != nil { |
| 157 |
// best position for error reporting |
| 158 |
pos := pos |
| 159 |
if i < len(xlist) { |
| 160 |
pos = syntax.StartPos(xlist[i]) |
| 161 |
} |
| 162 |
check.softErrorf(pos, InvalidTypeArg, "%s", err) |
| 163 |
} else { |
| 164 |
check.mono.recordInstance(check.pkg, pos, tparams, targs, xlist) |
| 165 |
} |
| 166 |
}).describef(pos, "verify instantiation") |
| 167 |
|
| 168 |
return inst |
| 169 |
} |
| 170 |
|
| 171 |
func (check *Checker) callExpr(x *operand, call *syntax.CallExpr) exprKind { |
| 172 |
var inst *syntax.IndexExpr // function instantiation, if any |
| 173 |
if iexpr, _ := call.Fun.(*syntax.IndexExpr); iexpr != nil { |
| 174 |
if check.indexExpr(x, iexpr) { |
| 175 |
// Delay function instantiation to argument checking, |
| 176 |
// where we combine type and value arguments for type |
| 177 |
// inference. |
| 178 |
assert(x.mode == value) |
| 179 |
inst = iexpr |
| 180 |
} |
| 181 |
x.expr = iexpr |
| 182 |
check.record(x) |
| 183 |
} else { |
| 184 |
check.exprOrType(x, call.Fun, true) |
| 185 |
} |
| 186 |
// x.typ may be generic |
| 187 |
|
| 188 |
switch x.mode { |
| 189 |
case invalid: |
| 190 |
check.use(call.ArgList...) |
| 191 |
x.expr = call |
| 192 |
return statement |
| 193 |
|
| 194 |
case typexpr: |
| 195 |
// conversion |
| 196 |
check.nonGeneric(nil, x) |
| 197 |
if x.mode == invalid { |
| 198 |
return conversion |
| 199 |
} |
| 200 |
T := x.typ |
| 201 |
x.mode = invalid |
| 202 |
switch n := len(call.ArgList); n { |
| 203 |
case 0: |
| 204 |
check.errorf(call, WrongArgCount, "missing argument in conversion to %s", T) |
| 205 |
case 1: |
| 206 |
check.expr(nil, x, call.ArgList[0]) |
| 207 |
if x.mode != invalid { |
| 208 |
if t, _ := T.Underlying().(*Interface); t != nil && !isTypeParam(T) { |
| 209 |
if !t.IsMethodSet() { |
| 210 |
check.errorf(call, MisplacedConstraintIface, "cannot use interface %s in conversion (contains specific type constraints or is comparable)", T) |
| 211 |
break |
| 212 |
} |
| 213 |
} |
| 214 |
if hasDots(call) { |
| 215 |
check.errorf(call.ArgList[0], BadDotDotDotSyntax, "invalid use of ... in conversion to %s", T) |
| 216 |
break |
| 217 |
} |
| 218 |
check.conversion(x, T) |
| 219 |
} |
| 220 |
default: |
| 221 |
check.use(call.ArgList...) |
| 222 |
check.errorf(call.ArgList[n-1], WrongArgCount, "too many arguments in conversion to %s", T) |
| 223 |
} |
| 224 |
x.expr = call |
| 225 |
return conversion |
| 226 |
|
| 227 |
case builtin: |
| 228 |
// no need to check for non-genericity here |
| 229 |
id := x.id |
| 230 |
if !check.builtin(x, call, id) { |
| 231 |
x.mode = invalid |
| 232 |
} |
| 233 |
x.expr = call |
| 234 |
// a non-constant result implies a function call |
| 235 |
if x.mode != invalid && x.mode != constant_ { |
| 236 |
check.hasCallOrRecv = true |
| 237 |
} |
| 238 |
return predeclaredFuncs[id].kind |
| 239 |
} |
| 240 |
|
| 241 |
// ordinary function/method call |
| 242 |
// signature may be generic |
| 243 |
cgocall := x.mode == cgofunc |
| 244 |
|
| 245 |
// If the operand type is a type parameter, all types in its type set |
| 246 |
// must have a common underlying type, which must be a signature. |
| 247 |
u, err := commonUnder(x.typ, func(t, u Type) *typeError { |
| 248 |
if _, ok := u.(*Signature); u != nil && !ok { |
| 249 |
return typeErrorf("%s is not a function", t) |
| 250 |
} |
| 251 |
return nil |
| 252 |
}) |
| 253 |
if err != nil { |
| 254 |
check.errorf(x, InvalidCall, invalidOp+"cannot call %s: %s", x, err.format(check)) |
| 255 |
x.mode = invalid |
| 256 |
x.expr = call |
| 257 |
return statement |
| 258 |
} |
| 259 |
sig := u.(*Signature) // u must be a signature per the commonUnder condition |
| 260 |
|
| 261 |
// Capture wasGeneric before sig is potentially instantiated below. |
| 262 |
wasGeneric := sig.TypeParams().Len() > 0 |
| 263 |
|
| 264 |
// evaluate type arguments, if any |
| 265 |
var xlist []syntax.Expr |
| 266 |
var targs []Type |
| 267 |
if inst != nil { |
| 268 |
xlist = syntax.UnpackListExpr(inst.Index) |
| 269 |
targs = check.typeList(xlist) |
| 270 |
if targs == nil { |
| 271 |
check.use(call.ArgList...) |
| 272 |
x.mode = invalid |
| 273 |
x.expr = call |
| 274 |
return statement |
| 275 |
} |
| 276 |
assert(len(targs) == len(xlist)) |
| 277 |
|
| 278 |
// check number of type arguments (got) vs number of type parameters (want) |
| 279 |
got, want := len(targs), sig.TypeParams().Len() |
| 280 |
if got > want { |
| 281 |
check.errorf(xlist[want], WrongTypeArgCount, "got %d type arguments but want %d", got, want) |
| 282 |
check.use(call.ArgList...) |
| 283 |
x.mode = invalid |
| 284 |
x.expr = call |
| 285 |
return statement |
| 286 |
} |
| 287 |
|
| 288 |
// If sig is generic and all type arguments are provided, preempt function |
| 289 |
// argument type inference by explicitly instantiating the signature. This |
| 290 |
// ensures that we record accurate type information for sig, even if there |
| 291 |
// is an error checking its arguments (for example, if an incorrect number |
| 292 |
// of arguments is supplied). |
| 293 |
if got == want && want > 0 { |
| 294 |
check.verifyVersionf(inst, go1_18, "function instantiation") |
| 295 |
sig = check.instantiateSignature(inst.Pos(), inst, sig, targs, xlist) |
| 296 |
// targs have been consumed; proceed with checking arguments of the |
| 297 |
// non-generic signature. |
| 298 |
targs = nil |
| 299 |
xlist = nil |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
// evaluate arguments |
| 304 |
args, atargs := check.genericExprList(call.ArgList) |
| 305 |
sig = check.arguments(call, sig, targs, xlist, args, atargs) |
| 306 |
|
| 307 |
if wasGeneric && sig.TypeParams().Len() == 0 { |
| 308 |
// update the recorded type of call.Fun to its instantiated type |
| 309 |
check.recordTypeAndValue(call.Fun, value, sig, nil) |
| 310 |
} |
| 311 |
|
| 312 |
// determine result |
| 313 |
switch sig.results.Len() { |
| 314 |
case 0: |
| 315 |
x.mode = novalue |
| 316 |
case 1: |
| 317 |
if cgocall { |
| 318 |
x.mode = commaerr |
| 319 |
} else { |
| 320 |
x.mode = value |
| 321 |
} |
| 322 |
x.typ = sig.results.vars[0].typ // unpack tuple |
| 323 |
default: |
| 324 |
x.mode = value |
| 325 |
x.typ = sig.results |
| 326 |
} |
| 327 |
x.expr = call |
| 328 |
check.hasCallOrRecv = true |
| 329 |
|
| 330 |
// if type inference failed, a parameterized result must be invalidated |
| 331 |
// (operands cannot have a parameterized type) |
| 332 |
if x.mode == value && sig.TypeParams().Len() > 0 && isParameterized(sig.TypeParams().list(), x.typ) { |
| 333 |
x.mode = invalid |
| 334 |
} |
| 335 |
|
| 336 |
return statement |
| 337 |
} |
| 338 |
|
| 339 |
// exprList evaluates a list of expressions and returns the corresponding operands. |
| 340 |
// A single-element expression list may evaluate to multiple operands. |
| 341 |
func (check *Checker) exprList(elist []syntax.Expr) (xlist []*operand) { |
| 342 |
if n := len(elist); n == 1 { |
| 343 |
xlist, _ = check.multiExpr(elist[0], false) |
| 344 |
} else if n > 1 { |
| 345 |
// multiple (possibly invalid) values |
| 346 |
xlist = make([]*operand, n) |
| 347 |
for i, e := range elist { |
| 348 |
var x operand |
| 349 |
check.expr(nil, &x, e) |
| 350 |
xlist[i] = &x |
| 351 |
} |
| 352 |
} |
| 353 |
return |
| 354 |
} |
| 355 |
|
| 356 |
// genericExprList is like exprList but result operands may be uninstantiated or partially |
| 357 |
// instantiated generic functions (where constraint information is insufficient to infer |
| 358 |
// the missing type arguments) for Go 1.21 and later. |
| 359 |
// For each non-generic or uninstantiated generic operand, the corresponding targsList and |
| 360 |
// elements do not exist (targsList is nil) or the elements are nil. |
| 361 |
// For each partially instantiated generic function operand, the corresponding |
| 362 |
// targsList elements are the operand's partial type arguments. |
| 363 |
func (check *Checker) genericExprList(elist []syntax.Expr) (resList []*operand, targsList [][]Type) { |
| 364 |
if debug { |
| 365 |
defer func() { |
| 366 |
// type arguments must only exist for partially instantiated functions |
| 367 |
for i, x := range resList { |
| 368 |
if i < len(targsList) { |
| 369 |
if n := len(targsList[i]); n > 0 { |
| 370 |
// x must be a partially instantiated function |
| 371 |
assert(n < x.typ.(*Signature).TypeParams().Len()) |
| 372 |
} |
| 373 |
} |
| 374 |
} |
| 375 |
}() |
| 376 |
} |
| 377 |
|
| 378 |
// Before Go 1.21, uninstantiated or partially instantiated argument functions are |
| 379 |
// nor permitted. Checker.funcInst must infer missing type arguments in that case. |
| 380 |
infer := true // for -lang < go1.21 |
| 381 |
n := len(elist) |
| 382 |
if n > 0 && check.allowVersion(go1_21) { |
| 383 |
infer = false |
| 384 |
} |
| 385 |
|
| 386 |
if n == 1 { |
| 387 |
// single value (possibly a partially instantiated function), or a multi-valued expression |
| 388 |
e := elist[0] |
| 389 |
var x operand |
| 390 |
if inst, _ := e.(*syntax.IndexExpr); inst != nil && check.indexExpr(&x, inst) { |
| 391 |
// x is a generic function. |
| 392 |
targs := check.funcInst(nil, x.Pos(), &x, inst, infer) |
| 393 |
if targs != nil { |
| 394 |
// x was not instantiated: collect the (partial) type arguments. |
| 395 |
targsList = [][]Type{targs} |
| 396 |
// Update x.expr so that we can record the partially instantiated function. |
| 397 |
x.expr = inst |
| 398 |
} else { |
| 399 |
// x was instantiated: we must record it here because we didn't |
| 400 |
// use the usual expression evaluators. |
| 401 |
check.record(&x) |
| 402 |
} |
| 403 |
resList = []*operand{&x} |
| 404 |
} else { |
| 405 |
// x is not a function instantiation (it may still be a generic function). |
| 406 |
check.rawExpr(nil, &x, e, nil, true) |
| 407 |
check.exclude(&x, 1<<novalue|1<<builtin|1<<typexpr) |
| 408 |
if t, ok := x.typ.(*Tuple); ok && x.mode != invalid { |
| 409 |
// x is a function call returning multiple values; it cannot be generic. |
| 410 |
resList = make([]*operand, t.Len()) |
| 411 |
for i, v := range t.vars { |
| 412 |
resList[i] = &operand{mode: value, expr: e, typ: v.typ} |
| 413 |
} |
| 414 |
} else { |
| 415 |
// x is exactly one value (possibly invalid or uninstantiated generic function). |
| 416 |
resList = []*operand{&x} |
| 417 |
} |
| 418 |
} |
| 419 |
} else if n > 1 { |
| 420 |
// multiple values |
| 421 |
resList = make([]*operand, n) |
| 422 |
targsList = make([][]Type, n) |
| 423 |
for i, e := range elist { |
| 424 |
var x operand |
| 425 |
if inst, _ := e.(*syntax.IndexExpr); inst != nil && check.indexExpr(&x, inst) { |
| 426 |
// x is a generic function. |
| 427 |
targs := check.funcInst(nil, x.Pos(), &x, inst, infer) |
| 428 |
if targs != nil { |
| 429 |
// x was not instantiated: collect the (partial) type arguments. |
| 430 |
targsList[i] = targs |
| 431 |
// Update x.expr so that we can record the partially instantiated function. |
| 432 |
x.expr = inst |
| 433 |
} else { |
| 434 |
// x was instantiated: we must record it here because we didn't |
| 435 |
// use the usual expression evaluators. |
| 436 |
check.record(&x) |
| 437 |
} |
| 438 |
} else { |
| 439 |
// x is exactly one value (possibly invalid or uninstantiated generic function). |
| 440 |
check.genericExpr(&x, e) |
| 441 |
} |
| 442 |
resList[i] = &x |
| 443 |
} |
| 444 |
} |
| 445 |
|
| 446 |
return |
| 447 |
} |
| 448 |
|
| 449 |
// arguments type-checks arguments passed to a function call with the given signature. |
| 450 |
// The function and its arguments may be generic, and possibly partially instantiated. |
| 451 |
// targs and xlist are the function's type arguments (and corresponding expressions). |
| 452 |
// args are the function arguments. If an argument args[i] is a partially instantiated |
| 453 |
// generic function, atargs[i] are the corresponding type arguments. |
| 454 |
// If the callee is variadic, arguments adjusts its signature to match the provided |
| 455 |
// arguments. The type parameters and arguments of the callee and all its arguments |
| 456 |
// are used together to infer any missing type arguments, and the callee and argument |
| 457 |
// functions are instantiated as necessary. |
| 458 |
// The result signature is the (possibly adjusted and instantiated) function signature. |
| 459 |
// If an error occurred, the result signature is the incoming sig. |
| 460 |
func (check *Checker) arguments(call *syntax.CallExpr, sig *Signature, targs []Type, xlist []syntax.Expr, args []*operand, atargs [][]Type) (rsig *Signature) { |
| 461 |
rsig = sig |
| 462 |
|
| 463 |
// Function call argument/parameter count requirements |
| 464 |
// |
| 465 |
// | standard call | dotdotdot call | |
| 466 |
// --------------+------------------+----------------+ |
| 467 |
// standard func | nargs == npars | invalid | |
| 468 |
// --------------+------------------+----------------+ |
| 469 |
// variadic func | nargs >= npars-1 | nargs == npars | |
| 470 |
// --------------+------------------+----------------+ |
| 471 |
|
| 472 |
nargs := len(args) |
| 473 |
npars := sig.params.Len() |
| 474 |
ddd := hasDots(call) |
| 475 |
|
| 476 |
// set up parameters |
| 477 |
sigParams := sig.params // adjusted for variadic functions (may be nil for empty parameter lists!) |
| 478 |
adjusted := false // indicates if sigParams is different from sig.params |
| 479 |
if sig.variadic { |
| 480 |
if ddd { |
| 481 |
// variadic_func(a, b, c...) |
| 482 |
if len(call.ArgList) == 1 && nargs > 1 { |
| 483 |
// f()... is not permitted if f() is multi-valued |
| 484 |
//check.errorf(call.Ellipsis, "cannot use ... with %d-valued %s", nargs, call.ArgList[0]) |
| 485 |
check.errorf(call, InvalidDotDotDot, "cannot use ... with %d-valued %s", nargs, call.ArgList[0]) |
| 486 |
return |
| 487 |
} |
| 488 |
} else { |
| 489 |
// variadic_func(a, b, c) |
| 490 |
if nargs >= npars-1 { |
| 491 |
// Create custom parameters for arguments: keep |
| 492 |
// the first npars-1 parameters and add one for |
| 493 |
// each argument mapping to the ... parameter. |
| 494 |
vars := make([]*Var, npars-1) // npars > 0 for variadic functions |
| 495 |
copy(vars, sig.params.vars) |
| 496 |
last := sig.params.vars[npars-1] |
| 497 |
typ := last.typ.(*Slice).elem |
| 498 |
for len(vars) < nargs { |
| 499 |
vars = append(vars, NewParam(last.pos, last.pkg, last.name, typ)) |
| 500 |
} |
| 501 |
sigParams = NewTuple(vars...) // possibly nil! |
| 502 |
adjusted = true |
| 503 |
npars = nargs |
| 504 |
} else { |
| 505 |
// nargs < npars-1 |
| 506 |
npars-- // for correct error message below |
| 507 |
} |
| 508 |
} |
| 509 |
} else { |
| 510 |
if ddd { |
| 511 |
// standard_func(a, b, c...) |
| 512 |
//check.errorf(call.Ellipsis, "cannot use ... in call to non-variadic %s", call.Fun) |
| 513 |
check.errorf(call, NonVariadicDotDotDot, "cannot use ... in call to non-variadic %s", call.Fun) |
| 514 |
return |
| 515 |
} |
| 516 |
// standard_func(a, b, c) |
| 517 |
} |
| 518 |
|
| 519 |
// check argument count |
| 520 |
if nargs != npars { |
| 521 |
var at poser = call |
| 522 |
qualifier := "not enough" |
| 523 |
if nargs > npars { |
| 524 |
at = args[npars].expr // report at first extra argument |
| 525 |
qualifier = "too many" |
| 526 |
} else if nargs > 0 { |
| 527 |
at = args[nargs-1].expr // report at last argument |
| 528 |
} |
| 529 |
// take care of empty parameter lists represented by nil tuples |
| 530 |
var params []*Var |
| 531 |
if sig.params != nil { |
| 532 |
params = sig.params.vars |
| 533 |
} |
| 534 |
err := check.newError(WrongArgCount) |
| 535 |
err.addf(at, "%s arguments in call to %s", qualifier, call.Fun) |
| 536 |
err.addf(nopos, "have %s", check.typesSummary(operandTypes(args), false, ddd)) |
| 537 |
err.addf(nopos, "want %s", check.typesSummary(varTypes(params), sig.variadic, false)) |
| 538 |
err.report() |
| 539 |
return |
| 540 |
} |
| 541 |
|
| 542 |
// collect type parameters of callee and generic function arguments |
| 543 |
var tparams []*TypeParam |
| 544 |
|
| 545 |
// collect type parameters of callee |
| 546 |
n := sig.TypeParams().Len() |
| 547 |
if n > 0 { |
| 548 |
if !check.allowVersion(go1_18) { |
| 549 |
if iexpr, _ := call.Fun.(*syntax.IndexExpr); iexpr != nil { |
| 550 |
check.versionErrorf(iexpr, go1_18, "function instantiation") |
| 551 |
} else { |
| 552 |
check.versionErrorf(call, go1_18, "implicit function instantiation") |
| 553 |
} |
| 554 |
} |
| 555 |
// rename type parameters to avoid problems with recursive calls |
| 556 |
var tmp Type |
| 557 |
tparams, tmp = check.renameTParams(call.Pos(), sig.TypeParams().list(), sigParams) |
| 558 |
sigParams = tmp.(*Tuple) |
| 559 |
// make sure targs and tparams have the same length |
| 560 |
for len(targs) < len(tparams) { |
| 561 |
targs = append(targs, nil) |
| 562 |
} |
| 563 |
} |
| 564 |
assert(len(tparams) == len(targs)) |
| 565 |
|
| 566 |
// collect type parameters from generic function arguments |
| 567 |
var genericArgs []int // indices of generic function arguments |
| 568 |
if enableReverseTypeInference { |
| 569 |
for i, arg := range args { |
| 570 |
// generic arguments cannot have a defined (*Named) type - no need for underlying type below |
| 571 |
if asig, _ := arg.typ.(*Signature); asig != nil && asig.TypeParams().Len() > 0 { |
| 572 |
// The argument type is a generic function signature. This type is |
| 573 |
// pointer-identical with (it's copied from) the type of the generic |
| 574 |
// function argument and thus the function object. |
| 575 |
// Before we change the type (type parameter renaming, below), make |
| 576 |
// a clone of it as otherwise we implicitly modify the object's type |
| 577 |
// (go.dev/issues/63260). |
| 578 |
asig = clone(asig) |
| 579 |
// Rename type parameters for cases like f(g, g); this gives each |
| 580 |
// generic function argument a unique type identity (go.dev/issues/59956). |
| 581 |
// TODO(gri) Consider only doing this if a function argument appears |
| 582 |
// multiple times, which is rare (possible optimization). |
| 583 |
atparams, tmp := check.renameTParams(call.Pos(), asig.TypeParams().list(), asig) |
| 584 |
asig = tmp.(*Signature) |
| 585 |
asig.tparams = &TypeParamList{atparams} // renameTParams doesn't touch associated type parameters |
| 586 |
arg.typ = asig // new type identity for the function argument |
| 587 |
tparams = append(tparams, atparams...) |
| 588 |
// add partial list of type arguments, if any |
| 589 |
if i < len(atargs) { |
| 590 |
targs = append(targs, atargs[i]...) |
| 591 |
} |
| 592 |
// make sure targs and tparams have the same length |
| 593 |
for len(targs) < len(tparams) { |
| 594 |
targs = append(targs, nil) |
| 595 |
} |
| 596 |
genericArgs = append(genericArgs, i) |
| 597 |
} |
| 598 |
} |
| 599 |
} |
| 600 |
assert(len(tparams) == len(targs)) |
| 601 |
|
| 602 |
// at the moment we only support implicit instantiations of argument functions |
| 603 |
_ = len(genericArgs) > 0 && check.verifyVersionf(args[genericArgs[0]], go1_21, "implicitly instantiated function as argument") |
| 604 |
|
| 605 |
// tparams holds the type parameters of the callee and generic function arguments, if any: |
| 606 |
// the first n type parameters belong to the callee, followed by mi type parameters for each |
| 607 |
// of the generic function arguments, where mi = args[i].typ.(*Signature).TypeParams().Len(). |
| 608 |
|
| 609 |
// infer missing type arguments of callee and function arguments |
| 610 |
if len(tparams) > 0 { |
| 611 |
err := check.newError(CannotInferTypeArgs) |
| 612 |
targs = check.infer(call.Pos(), tparams, targs, sigParams, args, false, err) |
| 613 |
if targs == nil { |
| 614 |
// TODO(gri) If infer inferred the first targs[:n], consider instantiating |
| 615 |
// the call signature for better error messages/gopls behavior. |
| 616 |
// Perhaps instantiate as much as we can, also for arguments. |
| 617 |
// This will require changes to how infer returns its results. |
| 618 |
if !err.empty() { |
| 619 |
check.errorf(err.pos(), CannotInferTypeArgs, "in call to %s, %s", call.Fun, err.msg()) |
| 620 |
} |
| 621 |
return |
| 622 |
} |
| 623 |
|
| 624 |
// update result signature: instantiate if needed |
| 625 |
if n > 0 { |
| 626 |
rsig = check.instantiateSignature(call.Pos(), call.Fun, sig, targs[:n], xlist) |
| 627 |
// If the callee's parameter list was adjusted we need to update (instantiate) |
| 628 |
// it separately. Otherwise we can simply use the result signature's parameter |
| 629 |
// list. |
| 630 |
if adjusted { |
| 631 |
sigParams = check.subst(call.Pos(), sigParams, makeSubstMap(tparams[:n], targs[:n]), nil, check.context()).(*Tuple) |
| 632 |
} else { |
| 633 |
sigParams = rsig.params |
| 634 |
} |
| 635 |
} |
| 636 |
|
| 637 |
// compute argument signatures: instantiate if needed |
| 638 |
j := n |
| 639 |
for _, i := range genericArgs { |
| 640 |
arg := args[i] |
| 641 |
asig := arg.typ.(*Signature) |
| 642 |
k := j + asig.TypeParams().Len() |
| 643 |
// targs[j:k] are the inferred type arguments for asig |
| 644 |
arg.typ = check.instantiateSignature(call.Pos(), arg.expr, asig, targs[j:k], nil) // TODO(gri) provide xlist if possible (partial instantiations) |
| 645 |
check.record(arg) // record here because we didn't use the usual expr evaluators |
| 646 |
j = k |
| 647 |
} |
| 648 |
} |
| 649 |
|
| 650 |
// check arguments |
| 651 |
if len(args) > 0 { |
| 652 |
context := check.sprintf("argument to %s", call.Fun) |
| 653 |
for i, a := range args { |
| 654 |
check.assignment(a, sigParams.vars[i].typ, context) |
| 655 |
} |
| 656 |
} |
| 657 |
|
| 658 |
return |
| 659 |
} |
| 660 |
|
| 661 |
var cgoPrefixes = [...]string{ |
| 662 |
"_Ciconst_", |
| 663 |
"_Cfconst_", |
| 664 |
"_Csconst_", |
| 665 |
"_Ctype_", |
| 666 |
"_Cvar_", // actually a pointer to the var |
| 667 |
"_Cfpvar_fp_", |
| 668 |
"_Cfunc_", |
| 669 |
"_Cmacro_", // function to evaluate the expanded expression |
| 670 |
} |
| 671 |
|
| 672 |
func (check *Checker) selector(x *operand, e *syntax.SelectorExpr, wantType bool) { |
| 673 |
// these must be declared before the "goto Error" statements |
| 674 |
var ( |
| 675 |
obj Object |
| 676 |
index []int |
| 677 |
indirect bool |
| 678 |
) |
| 679 |
|
| 680 |
sel := e.Sel.Value |
| 681 |
// If the identifier refers to a package, handle everything here |
| 682 |
// so we don't need a "package" mode for operands: package names |
| 683 |
// can only appear in qualified identifiers which are mapped to |
| 684 |
// selector expressions. |
| 685 |
if ident, ok := e.X.(*syntax.Name); ok { |
| 686 |
obj := check.lookup(ident.Value) |
| 687 |
if pname, _ := obj.(*PkgName); pname != nil { |
| 688 |
assert(pname.pkg == check.pkg) |
| 689 |
check.recordUse(ident, pname) |
| 690 |
check.usedPkgNames[pname] = true |
| 691 |
pkg := pname.imported |
| 692 |
|
| 693 |
var exp Object |
| 694 |
funcMode := value |
| 695 |
if pkg.cgo { |
| 696 |
// cgo special cases C.malloc: it's |
| 697 |
// rewritten to _CMalloc and does not |
| 698 |
// support two-result calls. |
| 699 |
if sel == "malloc" { |
| 700 |
sel = "_CMalloc" |
| 701 |
} else { |
| 702 |
funcMode = cgofunc |
| 703 |
} |
| 704 |
for _, prefix := range cgoPrefixes { |
| 705 |
// cgo objects are part of the current package (in file |
| 706 |
// _cgo_gotypes.go). Use regular lookup. |
| 707 |
exp = check.lookup(prefix + sel) |
| 708 |
if exp != nil { |
| 709 |
break |
| 710 |
} |
| 711 |
} |
| 712 |
if exp == nil { |
| 713 |
if isValidName(sel) { |
| 714 |
check.errorf(e.Sel, UndeclaredImportedName, "undefined: %s", syntax.Expr(e)) // cast to syntax.Expr to silence vet |
| 715 |
} |
| 716 |
goto Error |
| 717 |
} |
| 718 |
check.objDecl(exp) |
| 719 |
} else { |
| 720 |
exp = pkg.scope.Lookup(sel) |
| 721 |
if exp == nil { |
| 722 |
if !pkg.fake && isValidName(sel) { |
| 723 |
// Try to give a better error message when selector matches an object name ignoring case. |
| 724 |
exps := pkg.scope.lookupIgnoringCase(sel, true) |
| 725 |
if len(exps) >= 1 { |
| 726 |
// report just the first one |
| 727 |
check.errorf(e.Sel, UndeclaredImportedName, "undefined: %s (but have %s)", syntax.Expr(e), exps[0].Name()) |
| 728 |
} else { |
| 729 |
check.errorf(e.Sel, UndeclaredImportedName, "undefined: %s", syntax.Expr(e)) |
| 730 |
} |
| 731 |
} |
| 732 |
goto Error |
| 733 |
} |
| 734 |
if !exp.Exported() { |
| 735 |
check.errorf(e.Sel, UnexportedName, "name %s not exported by package %s", sel, pkg.name) |
| 736 |
// ok to continue |
| 737 |
} |
| 738 |
} |
| 739 |
check.recordUse(e.Sel, exp) |
| 740 |
|
| 741 |
// Simplified version of the code for *syntax.Names: |
| 742 |
// - imported objects are always fully initialized |
| 743 |
switch exp := exp.(type) { |
| 744 |
case *Const: |
| 745 |
assert(exp.Val() != nil) |
| 746 |
x.mode = constant_ |
| 747 |
x.typ = exp.typ |
| 748 |
x.val = exp.val |
| 749 |
case *TypeName: |
| 750 |
x.mode = typexpr |
| 751 |
x.typ = exp.typ |
| 752 |
case *Var: |
| 753 |
x.mode = variable |
| 754 |
x.typ = exp.typ |
| 755 |
if pkg.cgo && strings.HasPrefix(exp.name, "_Cvar_") { |
| 756 |
x.typ = x.typ.(*Pointer).base |
| 757 |
} |
| 758 |
case *Func: |
| 759 |
x.mode = funcMode |
| 760 |
x.typ = exp.typ |
| 761 |
if pkg.cgo && strings.HasPrefix(exp.name, "_Cmacro_") { |
| 762 |
x.mode = value |
| 763 |
x.typ = x.typ.(*Signature).results.vars[0].typ |
| 764 |
} |
| 765 |
case *Builtin: |
| 766 |
x.mode = builtin |
| 767 |
x.typ = exp.typ |
| 768 |
x.id = exp.id |
| 769 |
default: |
| 770 |
check.dump("%v: unexpected object %v", atPos(e.Sel), exp) |
| 771 |
panic("unreachable") |
| 772 |
} |
| 773 |
x.expr = e |
| 774 |
return |
| 775 |
} |
| 776 |
} |
| 777 |
|
| 778 |
check.exprOrType(x, e.X, false) |
| 779 |
switch x.mode { |
| 780 |
case builtin: |
| 781 |
check.errorf(e.Pos(), UncalledBuiltin, "invalid use of %s in selector expression", x) |
| 782 |
goto Error |
| 783 |
case invalid: |
| 784 |
goto Error |
| 785 |
} |
| 786 |
|
| 787 |
// Avoid crashing when checking an invalid selector in a method declaration |
| 788 |
// (i.e., where def is not set): |
| 789 |
// |
| 790 |
// type S[T any] struct{} |
| 791 |
// type V = S[any] |
| 792 |
// func (fs *S[T]) M(x V.M) {} |
| 793 |
// |
| 794 |
// All codepaths below return a non-type expression. If we get here while |
| 795 |
// expecting a type expression, it is an error. |
| 796 |
// |
| 797 |
// See go.dev/issue/57522 for more details. |
| 798 |
// |
| 799 |
// TODO(rfindley): We should do better by refusing to check selectors in all cases where |
| 800 |
// x.typ is incomplete. |
| 801 |
if wantType { |
| 802 |
check.errorf(e.Sel, NotAType, "%s is not a type", syntax.Expr(e)) |
| 803 |
goto Error |
| 804 |
} |
| 805 |
|
| 806 |
obj, index, indirect = lookupFieldOrMethod(x.typ, x.mode == variable, check.pkg, sel, false) |
| 807 |
if obj == nil { |
| 808 |
// Don't report another error if the underlying type was invalid (go.dev/issue/49541). |
| 809 |
if !isValid(x.typ.Underlying()) { |
| 810 |
goto Error |
| 811 |
} |
| 812 |
|
| 813 |
if index != nil { |
| 814 |
// TODO(gri) should provide actual type where the conflict happens |
| 815 |
check.errorf(e.Sel, AmbiguousSelector, "ambiguous selector %s.%s", x.expr, sel) |
| 816 |
goto Error |
| 817 |
} |
| 818 |
|
| 819 |
if indirect { |
| 820 |
if x.mode == typexpr { |
| 821 |
check.errorf(e.Sel, InvalidMethodExpr, "invalid method expression %s.%s (needs pointer receiver (*%s).%s)", x.typ, sel, x.typ, sel) |
| 822 |
} else { |
| 823 |
check.errorf(e.Sel, InvalidMethodExpr, "cannot call pointer method %s on %s", sel, x.typ) |
| 824 |
} |
| 825 |
goto Error |
| 826 |
} |
| 827 |
|
| 828 |
var why string |
| 829 |
if isInterfacePtr(x.typ) { |
| 830 |
why = check.interfacePtrError(x.typ) |
| 831 |
} else { |
| 832 |
alt, _, _ := lookupFieldOrMethod(x.typ, x.mode == variable, check.pkg, sel, true) |
| 833 |
why = check.lookupError(x.typ, sel, alt, false) |
| 834 |
} |
| 835 |
check.errorf(e.Sel, MissingFieldOrMethod, "%s.%s undefined (%s)", x.expr, sel, why) |
| 836 |
goto Error |
| 837 |
} |
| 838 |
|
| 839 |
// methods may not have a fully set up signature yet |
| 840 |
if m, _ := obj.(*Func); m != nil { |
| 841 |
check.objDecl(m) |
| 842 |
} |
| 843 |
|
| 844 |
if x.mode == typexpr { |
| 845 |
// method expression |
| 846 |
m, _ := obj.(*Func) |
| 847 |
if m == nil { |
| 848 |
check.errorf(e.Sel, MissingFieldOrMethod, "%s.%s undefined (type %s has no method %s)", x.expr, sel, x.typ, sel) |
| 849 |
goto Error |
| 850 |
} |
| 851 |
|
| 852 |
check.recordSelection(e, MethodExpr, x.typ, m, index, indirect) |
| 853 |
|
| 854 |
sig := m.typ.(*Signature) |
| 855 |
if sig.recv == nil { |
| 856 |
check.error(e, InvalidDeclCycle, "illegal cycle in method declaration") |
| 857 |
goto Error |
| 858 |
} |
| 859 |
|
| 860 |
// The receiver type becomes the type of the first function |
| 861 |
// argument of the method expression's function type. |
| 862 |
var params []*Var |
| 863 |
if sig.params != nil { |
| 864 |
params = sig.params.vars |
| 865 |
} |
| 866 |
// Be consistent about named/unnamed parameters. This is not needed |
| 867 |
// for type-checking, but the newly constructed signature may appear |
| 868 |
// in an error message and then have mixed named/unnamed parameters. |
| 869 |
// (An alternative would be to not print parameter names in errors, |
| 870 |
// but it's useful to see them; this is cheap and method expressions |
| 871 |
// are rare.) |
| 872 |
name := "" |
| 873 |
if len(params) > 0 && params[0].name != "" { |
| 874 |
// name needed |
| 875 |
name = sig.recv.name |
| 876 |
if name == "" { |
| 877 |
name = "_" |
| 878 |
} |
| 879 |
} |
| 880 |
params = append([]*Var{NewParam(sig.recv.pos, sig.recv.pkg, name, x.typ)}, params...) |
| 881 |
x.mode = value |
| 882 |
x.typ = &Signature{ |
| 883 |
tparams: sig.tparams, |
| 884 |
params: NewTuple(params...), |
| 885 |
results: sig.results, |
| 886 |
variadic: sig.variadic, |
| 887 |
} |
| 888 |
|
| 889 |
check.addDeclDep(m) |
| 890 |
|
| 891 |
} else { |
| 892 |
// regular selector |
| 893 |
switch obj := obj.(type) { |
| 894 |
case *Var: |
| 895 |
check.recordSelection(e, FieldVal, x.typ, obj, index, indirect) |
| 896 |
if x.mode == variable || indirect { |
| 897 |
x.mode = variable |
| 898 |
} else { |
| 899 |
x.mode = value |
| 900 |
} |
| 901 |
x.typ = obj.typ |
| 902 |
|
| 903 |
case *Func: |
| 904 |
// TODO(gri) If we needed to take into account the receiver's |
| 905 |
// addressability, should we report the type &(x.typ) instead? |
| 906 |
check.recordSelection(e, MethodVal, x.typ, obj, index, indirect) |
| 907 |
|
| 908 |
x.mode = value |
| 909 |
|
| 910 |
// remove receiver |
| 911 |
sig := *obj.typ.(*Signature) |
| 912 |
sig.recv = nil |
| 913 |
x.typ = &sig |
| 914 |
|
| 915 |
check.addDeclDep(obj) |
| 916 |
|
| 917 |
default: |
| 918 |
panic("unreachable") |
| 919 |
} |
| 920 |
} |
| 921 |
|
| 922 |
// everything went well |
| 923 |
x.expr = e |
| 924 |
return |
| 925 |
|
| 926 |
Error: |
| 927 |
x.mode = invalid |
| 928 |
x.typ = Typ[Invalid] |
| 929 |
x.expr = e |
| 930 |
} |
| 931 |
|
| 932 |
// use type-checks each argument. |
| 933 |
// Useful to make sure expressions are evaluated |
| 934 |
// (and variables are "used") in the presence of |
| 935 |
// other errors. Arguments may be nil. |
| 936 |
// Reports if all arguments evaluated without error. |
| 937 |
func (check *Checker) use(args ...syntax.Expr) bool { return check.useN(args, false) } |
| 938 |
|
| 939 |
// useLHS is like use, but doesn't "use" top-level identifiers. |
| 940 |
// It should be called instead of use if the arguments are |
| 941 |
// expressions on the lhs of an assignment. |
| 942 |
func (check *Checker) useLHS(args ...syntax.Expr) bool { return check.useN(args, true) } |
| 943 |
|
| 944 |
func (check *Checker) useN(args []syntax.Expr, lhs bool) bool { |
| 945 |
ok := true |
| 946 |
for _, e := range args { |
| 947 |
if !check.use1(e, lhs) { |
| 948 |
ok = false |
| 949 |
} |
| 950 |
} |
| 951 |
return ok |
| 952 |
} |
| 953 |
|
| 954 |
func (check *Checker) use1(e syntax.Expr, lhs bool) bool { |
| 955 |
var x operand |
| 956 |
x.mode = value // anything but invalid |
| 957 |
switch n := syntax.Unparen(e).(type) { |
| 958 |
case nil: |
| 959 |
// nothing to do |
| 960 |
case *syntax.Name: |
| 961 |
// don't report an error evaluating blank |
| 962 |
if n.Value == "_" { |
| 963 |
break |
| 964 |
} |
| 965 |
// If the lhs is an identifier denoting a variable v, this assignment |
| 966 |
// is not a 'use' of v. Remember current value of v.used and restore |
| 967 |
// after evaluating the lhs via check.rawExpr. |
| 968 |
var v *Var |
| 969 |
var v_used bool |
| 970 |
if lhs { |
| 971 |
if obj := check.lookup(n.Value); obj != nil { |
| 972 |
// It's ok to mark non-local variables, but ignore variables |
| 973 |
// from other packages to avoid potential race conditions with |
| 974 |
// dot-imported variables. |
| 975 |
if w, _ := obj.(*Var); w != nil && w.pkg == check.pkg { |
| 976 |
v = w |
| 977 |
v_used = check.usedVars[v] |
| 978 |
} |
| 979 |
} |
| 980 |
} |
| 981 |
check.exprOrType(&x, n, true) |
| 982 |
if v != nil { |
| 983 |
check.usedVars[v] = v_used // restore v.used |
| 984 |
} |
| 985 |
case *syntax.ListExpr: |
| 986 |
return check.useN(n.ElemList, lhs) |
| 987 |
default: |
| 988 |
check.rawExpr(nil, &x, e, nil, true) |
| 989 |
} |
| 990 |
return x.mode != invalid |
| 991 |
} |