github.com/mattn/go@v0.0.0-20171011075504-07f7db3ea99f/src/go/types/call.go (about) 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 types 8 9 import ( 10 "go/ast" 11 "go/token" 12 ) 13 14 func (check *Checker) call(x *operand, e *ast.CallExpr) exprKind { 15 check.exprOrType(x, e.Fun) 16 17 switch x.mode { 18 case invalid: 19 check.use(e.Args...) 20 x.mode = invalid 21 x.expr = e 22 return statement 23 24 case typexpr: 25 // conversion 26 T := x.typ 27 x.mode = invalid 28 switch n := len(e.Args); n { 29 case 0: 30 check.errorf(e.Rparen, "missing argument in conversion to %s", T) 31 case 1: 32 check.expr(x, e.Args[0]) 33 if x.mode != invalid { 34 check.conversion(x, T) 35 } 36 default: 37 check.errorf(e.Args[n-1].Pos(), "too many arguments in conversion to %s", T) 38 } 39 x.expr = e 40 return conversion 41 42 case builtin: 43 id := x.id 44 if !check.builtin(x, e, id) { 45 x.mode = invalid 46 } 47 x.expr = e 48 // a non-constant result implies a function call 49 if x.mode != invalid && x.mode != constant_ { 50 check.hasCallOrRecv = true 51 } 52 return predeclaredFuncs[id].kind 53 54 default: 55 // function/method call 56 sig, _ := x.typ.Underlying().(*Signature) 57 if sig == nil { 58 check.invalidOp(x.pos(), "cannot call non-function %s", x) 59 x.mode = invalid 60 x.expr = e 61 return statement 62 } 63 64 arg, n, _ := unpack(func(x *operand, i int) { check.multiExpr(x, e.Args[i]) }, len(e.Args), false) 65 if arg != nil { 66 check.arguments(x, e, sig, arg, n) 67 } else { 68 x.mode = invalid 69 } 70 71 // determine result 72 switch sig.results.Len() { 73 case 0: 74 x.mode = novalue 75 case 1: 76 x.mode = value 77 x.typ = sig.results.vars[0].typ // unpack tuple 78 default: 79 x.mode = value 80 x.typ = sig.results 81 } 82 83 x.expr = e 84 check.hasCallOrRecv = true 85 86 return statement 87 } 88 } 89 90 // use type-checks each argument. 91 // Useful to make sure expressions are evaluated 92 // (and variables are "used") in the presence of other errors. 93 func (check *Checker) use(arg ...ast.Expr) { 94 var x operand 95 for _, e := range arg { 96 if e != nil { // be safe 97 check.rawExpr(&x, e, nil) 98 } 99 } 100 } 101 102 // useGetter is like use, but takes a getter instead of a list of expressions. 103 // It should be called instead of use if a getter is present to avoid repeated 104 // evaluation of the first argument (since the getter was likely obtained via 105 // unpack, which may have evaluated the first argument already). 106 func (check *Checker) useGetter(get getter, n int) { 107 var x operand 108 for i := 0; i < n; i++ { 109 get(&x, i) 110 } 111 } 112 113 // A getter sets x as the i'th operand, where 0 <= i < n and n is the total 114 // number of operands (context-specific, and maintained elsewhere). A getter 115 // type-checks the i'th operand; the details of the actual check are getter- 116 // specific. 117 type getter func(x *operand, i int) 118 119 // unpack takes a getter get and a number of operands n. If n == 1, unpack 120 // calls the incoming getter for the first operand. If that operand is 121 // invalid, unpack returns (nil, 0, false). Otherwise, if that operand is a 122 // function call, or a comma-ok expression and allowCommaOk is set, the result 123 // is a new getter and operand count providing access to the function results, 124 // or comma-ok values, respectively. The third result value reports if it 125 // is indeed the comma-ok case. In all other cases, the incoming getter and 126 // operand count are returned unchanged, and the third result value is false. 127 // 128 // In other words, if there's exactly one operand that - after type-checking 129 // by calling get - stands for multiple operands, the resulting getter provides 130 // access to those operands instead. 131 // 132 // If the returned getter is called at most once for a given operand index i 133 // (including i == 0), that operand is guaranteed to cause only one call of 134 // the incoming getter with that i. 135 // 136 func unpack(get getter, n int, allowCommaOk bool) (getter, int, bool) { 137 if n != 1 { 138 // zero or multiple values 139 return get, n, false 140 } 141 // possibly result of an n-valued function call or comma,ok value 142 var x0 operand 143 get(&x0, 0) 144 if x0.mode == invalid { 145 return nil, 0, false 146 } 147 148 if t, ok := x0.typ.(*Tuple); ok { 149 // result of an n-valued function call 150 return func(x *operand, i int) { 151 x.mode = value 152 x.expr = x0.expr 153 x.typ = t.At(i).typ 154 }, t.Len(), false 155 } 156 157 if x0.mode == mapindex || x0.mode == commaok { 158 // comma-ok value 159 if allowCommaOk { 160 a := [2]Type{x0.typ, Typ[UntypedBool]} 161 return func(x *operand, i int) { 162 x.mode = value 163 x.expr = x0.expr 164 x.typ = a[i] 165 }, 2, true 166 } 167 x0.mode = value 168 } 169 170 // single value 171 return func(x *operand, i int) { 172 if i != 0 { 173 unreachable() 174 } 175 *x = x0 176 }, 1, false 177 } 178 179 // arguments checks argument passing for the call with the given signature. 180 // The arg function provides the operand for the i'th argument. 181 func (check *Checker) arguments(x *operand, call *ast.CallExpr, sig *Signature, arg getter, n int) { 182 if call.Ellipsis.IsValid() { 183 // last argument is of the form x... 184 if !sig.variadic { 185 check.errorf(call.Ellipsis, "cannot use ... in call to non-variadic %s", call.Fun) 186 check.useGetter(arg, n) 187 return 188 } 189 if len(call.Args) == 1 && n > 1 { 190 // f()... is not permitted if f() is multi-valued 191 check.errorf(call.Ellipsis, "cannot use ... with %d-valued %s", n, call.Args[0]) 192 check.useGetter(arg, n) 193 return 194 } 195 } 196 197 // evaluate arguments 198 for i := 0; i < n; i++ { 199 arg(x, i) 200 if x.mode != invalid { 201 var ellipsis token.Pos 202 if i == n-1 && call.Ellipsis.IsValid() { 203 ellipsis = call.Ellipsis 204 } 205 check.argument(call.Fun, sig, i, x, ellipsis) 206 } 207 } 208 209 // check argument count 210 if sig.variadic { 211 // a variadic function accepts an "empty" 212 // last argument: count one extra 213 n++ 214 } 215 if n < sig.params.Len() { 216 check.errorf(call.Rparen, "too few arguments in call to %s", call.Fun) 217 // ok to continue 218 } 219 } 220 221 // argument checks passing of argument x to the i'th parameter of the given signature. 222 // If ellipsis is valid, the argument is followed by ... at that position in the call. 223 func (check *Checker) argument(fun ast.Expr, sig *Signature, i int, x *operand, ellipsis token.Pos) { 224 check.singleValue(x) 225 if x.mode == invalid { 226 return 227 } 228 229 n := sig.params.Len() 230 231 // determine parameter type 232 var typ Type 233 switch { 234 case i < n: 235 typ = sig.params.vars[i].typ 236 case sig.variadic: 237 typ = sig.params.vars[n-1].typ 238 if debug { 239 if _, ok := typ.(*Slice); !ok { 240 check.dump("%s: expected unnamed slice type, got %s", sig.params.vars[n-1].Pos(), typ) 241 } 242 } 243 default: 244 check.errorf(x.pos(), "too many arguments") 245 return 246 } 247 248 if ellipsis.IsValid() { 249 // argument is of the form x... and x is single-valued 250 if i != n-1 { 251 check.errorf(ellipsis, "can only use ... with matching parameter") 252 return 253 } 254 if _, ok := x.typ.Underlying().(*Slice); !ok && x.typ != Typ[UntypedNil] { // see issue #18268 255 check.errorf(x.pos(), "cannot use %s as parameter of type %s", x, typ) 256 return 257 } 258 } else if sig.variadic && i >= n-1 { 259 // use the variadic parameter slice's element type 260 typ = typ.(*Slice).elem 261 } 262 263 check.assignment(x, typ, check.sprintf("argument to %s", fun)) 264 } 265 266 func (check *Checker) selector(x *operand, e *ast.SelectorExpr) { 267 // these must be declared before the "goto Error" statements 268 var ( 269 obj Object 270 index []int 271 indirect bool 272 ) 273 274 sel := e.Sel.Name 275 // If the identifier refers to a package, handle everything here 276 // so we don't need a "package" mode for operands: package names 277 // can only appear in qualified identifiers which are mapped to 278 // selector expressions. 279 if ident, ok := e.X.(*ast.Ident); ok { 280 _, obj := check.scope.LookupParent(ident.Name, check.pos) 281 if pname, _ := obj.(*PkgName); pname != nil { 282 assert(pname.pkg == check.pkg) 283 check.recordUse(ident, pname) 284 pname.used = true 285 pkg := pname.imported 286 exp := pkg.scope.Lookup(sel) 287 if exp == nil { 288 if !pkg.fake { 289 check.errorf(e.Pos(), "%s not declared by package %s", sel, pkg.name) 290 } 291 goto Error 292 } 293 if !exp.Exported() { 294 check.errorf(e.Pos(), "%s not exported by package %s", sel, pkg.name) 295 // ok to continue 296 } 297 check.recordUse(e.Sel, exp) 298 299 // Simplified version of the code for *ast.Idents: 300 // - imported objects are always fully initialized 301 switch exp := exp.(type) { 302 case *Const: 303 assert(exp.Val() != nil) 304 x.mode = constant_ 305 x.typ = exp.typ 306 x.val = exp.val 307 case *TypeName: 308 x.mode = typexpr 309 x.typ = exp.typ 310 case *Var: 311 x.mode = variable 312 x.typ = exp.typ 313 case *Func: 314 x.mode = value 315 x.typ = exp.typ 316 case *Builtin: 317 x.mode = builtin 318 x.typ = exp.typ 319 x.id = exp.id 320 default: 321 check.dump("unexpected object %v", exp) 322 unreachable() 323 } 324 x.expr = e 325 return 326 } 327 } 328 329 check.exprOrType(x, e.X) 330 if x.mode == invalid { 331 goto Error 332 } 333 334 obj, index, indirect = LookupFieldOrMethod(x.typ, x.mode == variable, check.pkg, sel) 335 if obj == nil { 336 switch { 337 case index != nil: 338 // TODO(gri) should provide actual type where the conflict happens 339 check.invalidOp(e.Pos(), "ambiguous selector %s", sel) 340 case indirect: 341 check.invalidOp(e.Pos(), "%s is not in method set of %s", sel, x.typ) 342 default: 343 check.invalidOp(e.Pos(), "%s has no field or method %s", x, sel) 344 } 345 goto Error 346 } 347 348 if x.mode == typexpr { 349 // method expression 350 m, _ := obj.(*Func) 351 if m == nil { 352 check.invalidOp(e.Pos(), "%s has no method %s", x, sel) 353 goto Error 354 } 355 356 check.recordSelection(e, MethodExpr, x.typ, m, index, indirect) 357 358 // the receiver type becomes the type of the first function 359 // argument of the method expression's function type 360 var params []*Var 361 sig := m.typ.(*Signature) 362 if sig.params != nil { 363 params = sig.params.vars 364 } 365 x.mode = value 366 x.typ = &Signature{ 367 params: NewTuple(append([]*Var{NewVar(token.NoPos, check.pkg, "", x.typ)}, params...)...), 368 results: sig.results, 369 variadic: sig.variadic, 370 } 371 372 check.addDeclDep(m) 373 374 } else { 375 // regular selector 376 switch obj := obj.(type) { 377 case *Var: 378 check.recordSelection(e, FieldVal, x.typ, obj, index, indirect) 379 if x.mode == variable || indirect { 380 x.mode = variable 381 } else { 382 x.mode = value 383 } 384 x.typ = obj.typ 385 386 case *Func: 387 // TODO(gri) If we needed to take into account the receiver's 388 // addressability, should we report the type &(x.typ) instead? 389 check.recordSelection(e, MethodVal, x.typ, obj, index, indirect) 390 391 if debug { 392 // Verify that LookupFieldOrMethod and MethodSet.Lookup agree. 393 typ := x.typ 394 if x.mode == variable { 395 // If typ is not an (unnamed) pointer or an interface, 396 // use *typ instead, because the method set of *typ 397 // includes the methods of typ. 398 // Variables are addressable, so we can always take their 399 // address. 400 if _, ok := typ.(*Pointer); !ok && !IsInterface(typ) { 401 typ = &Pointer{base: typ} 402 } 403 } 404 // If we created a synthetic pointer type above, we will throw 405 // away the method set computed here after use. 406 // TODO(gri) Method set computation should probably always compute 407 // both, the value and the pointer receiver method set and represent 408 // them in a single structure. 409 // TODO(gri) Consider also using a method set cache for the lifetime 410 // of checker once we rely on MethodSet lookup instead of individual 411 // lookup. 412 mset := NewMethodSet(typ) 413 if m := mset.Lookup(check.pkg, sel); m == nil || m.obj != obj { 414 check.dump("%s: (%s).%v -> %s", e.Pos(), typ, obj.name, m) 415 check.dump("%s\n", mset) 416 panic("method sets and lookup don't agree") 417 } 418 } 419 420 x.mode = value 421 422 // remove receiver 423 sig := *obj.typ.(*Signature) 424 sig.recv = nil 425 x.typ = &sig 426 427 check.addDeclDep(obj) 428 429 default: 430 unreachable() 431 } 432 } 433 434 // everything went well 435 x.expr = e 436 return 437 438 Error: 439 x.mode = invalid 440 x.expr = e 441 }