github.com/mattn/go@v0.0.0-20171011075504-07f7db3ea99f/src/go/types/stmt.go (about) 1 // Copyright 2012 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 statements. 6 7 package types 8 9 import ( 10 "fmt" 11 "go/ast" 12 "go/constant" 13 "go/token" 14 ) 15 16 func (check *Checker) funcBody(decl *declInfo, name string, sig *Signature, body *ast.BlockStmt) { 17 if trace { 18 if name == "" { 19 name = "<function literal>" 20 } 21 fmt.Printf("--- %s: %s {\n", name, sig) 22 defer fmt.Println("--- <end>") 23 } 24 25 // set function scope extent 26 sig.scope.pos = body.Pos() 27 sig.scope.end = body.End() 28 29 // save/restore current context and setup function context 30 // (and use 0 indentation at function start) 31 defer func(ctxt context, indent int) { 32 check.context = ctxt 33 check.indent = indent 34 }(check.context, check.indent) 35 check.context = context{ 36 decl: decl, 37 scope: sig.scope, 38 sig: sig, 39 } 40 check.indent = 0 41 42 check.stmtList(0, body.List) 43 44 if check.hasLabel { 45 check.labels(body) 46 } 47 48 if sig.results.Len() > 0 && !check.isTerminating(body, "") { 49 check.error(body.Rbrace, "missing return") 50 } 51 52 // spec: "Implementation restriction: A compiler may make it illegal to 53 // declare a variable inside a function body if the variable is never used." 54 // (One could check each scope after use, but that distributes this check 55 // over several places because CloseScope is not always called explicitly.) 56 check.usage(sig.scope) 57 } 58 59 func (check *Checker) usage(scope *Scope) { 60 for _, obj := range scope.elems { 61 if v, _ := obj.(*Var); v != nil && !v.used { 62 check.softErrorf(v.pos, "%s declared but not used", v.name) 63 } 64 } 65 for _, scope := range scope.children { 66 check.usage(scope) 67 } 68 } 69 70 // stmtContext is a bitset describing which 71 // control-flow statements are permissible, 72 // and provides additional context information 73 // for better error messages. 74 type stmtContext uint 75 76 const ( 77 // permissible control-flow statements 78 breakOk stmtContext = 1 << iota 79 continueOk 80 fallthroughOk 81 82 // additional context information 83 finalSwitchCase 84 ) 85 86 func (check *Checker) simpleStmt(s ast.Stmt) { 87 if s != nil { 88 check.stmt(0, s) 89 } 90 } 91 92 func trimTrailingEmptyStmts(list []ast.Stmt) []ast.Stmt { 93 for i := len(list); i > 0; i-- { 94 if _, ok := list[i-1].(*ast.EmptyStmt); !ok { 95 return list[:i] 96 } 97 } 98 return nil 99 } 100 101 func (check *Checker) stmtList(ctxt stmtContext, list []ast.Stmt) { 102 ok := ctxt&fallthroughOk != 0 103 inner := ctxt &^ fallthroughOk 104 list = trimTrailingEmptyStmts(list) // trailing empty statements are "invisible" to fallthrough analysis 105 for i, s := range list { 106 inner := inner 107 if ok && i+1 == len(list) { 108 inner |= fallthroughOk 109 } 110 check.stmt(inner, s) 111 } 112 } 113 114 func (check *Checker) multipleDefaults(list []ast.Stmt) { 115 var first ast.Stmt 116 for _, s := range list { 117 var d ast.Stmt 118 switch c := s.(type) { 119 case *ast.CaseClause: 120 if len(c.List) == 0 { 121 d = s 122 } 123 case *ast.CommClause: 124 if c.Comm == nil { 125 d = s 126 } 127 default: 128 check.invalidAST(s.Pos(), "case/communication clause expected") 129 } 130 if d != nil { 131 if first != nil { 132 check.errorf(d.Pos(), "multiple defaults (first at %s)", check.fset.Position(first.Pos())) 133 } else { 134 first = d 135 } 136 } 137 } 138 } 139 140 func (check *Checker) openScope(s ast.Stmt, comment string) { 141 scope := NewScope(check.scope, s.Pos(), s.End(), comment) 142 check.recordScope(s, scope) 143 check.scope = scope 144 } 145 146 func (check *Checker) closeScope() { 147 check.scope = check.scope.Parent() 148 } 149 150 func assignOp(op token.Token) token.Token { 151 // token_test.go verifies the token ordering this function relies on 152 if token.ADD_ASSIGN <= op && op <= token.AND_NOT_ASSIGN { 153 return op + (token.ADD - token.ADD_ASSIGN) 154 } 155 return token.ILLEGAL 156 } 157 158 func (check *Checker) suspendedCall(keyword string, call *ast.CallExpr) { 159 var x operand 160 var msg string 161 switch check.rawExpr(&x, call, nil) { 162 case conversion: 163 msg = "requires function call, not conversion" 164 case expression: 165 msg = "discards result of" 166 case statement: 167 return 168 default: 169 unreachable() 170 } 171 check.errorf(x.pos(), "%s %s %s", keyword, msg, &x) 172 } 173 174 // goVal returns the Go value for val, or nil. 175 func goVal(val constant.Value) interface{} { 176 // val should exist, but be conservative and check 177 if val == nil { 178 return nil 179 } 180 // Match implementation restriction of other compilers. 181 // gc only checks duplicates for integer, floating-point 182 // and string values, so only create Go values for these 183 // types. 184 switch val.Kind() { 185 case constant.Int: 186 if x, ok := constant.Int64Val(val); ok { 187 return x 188 } 189 if x, ok := constant.Uint64Val(val); ok { 190 return x 191 } 192 case constant.Float: 193 if x, ok := constant.Float64Val(val); ok { 194 return x 195 } 196 case constant.String: 197 return constant.StringVal(val) 198 } 199 return nil 200 } 201 202 // A valueMap maps a case value (of a basic Go type) to a list of positions 203 // where the same case value appeared, together with the corresponding case 204 // types. 205 // Since two case values may have the same "underlying" value but different 206 // types we need to also check the value's types (e.g., byte(1) vs myByte(1)) 207 // when the switch expression is of interface type. 208 type ( 209 valueMap map[interface{}][]valueType // underlying Go value -> valueType 210 valueType struct { 211 pos token.Pos 212 typ Type 213 } 214 ) 215 216 func (check *Checker) caseValues(x *operand, values []ast.Expr, seen valueMap) { 217 L: 218 for _, e := range values { 219 var v operand 220 check.expr(&v, e) 221 if x.mode == invalid || v.mode == invalid { 222 continue L 223 } 224 check.convertUntyped(&v, x.typ) 225 if v.mode == invalid { 226 continue L 227 } 228 // Order matters: By comparing v against x, error positions are at the case values. 229 res := v // keep original v unchanged 230 check.comparison(&res, x, token.EQL) 231 if res.mode == invalid { 232 continue L 233 } 234 if v.mode != constant_ { 235 continue L // we're done 236 } 237 // look for duplicate values 238 if val := goVal(v.val); val != nil { 239 // look for duplicate types for a given value 240 // (quadratic algorithm, but these lists tend to be very short) 241 for _, vt := range seen[val] { 242 if Identical(v.typ, vt.typ) { 243 check.errorf(v.pos(), "duplicate case %s in expression switch", &v) 244 check.error(vt.pos, "\tprevious case") // secondary error, \t indented 245 continue L 246 } 247 } 248 seen[val] = append(seen[val], valueType{v.pos(), v.typ}) 249 } 250 } 251 } 252 253 func (check *Checker) caseTypes(x *operand, xtyp *Interface, types []ast.Expr, seen map[Type]token.Pos) (T Type) { 254 L: 255 for _, e := range types { 256 T = check.typOrNil(e) 257 if T == Typ[Invalid] { 258 continue L 259 } 260 // look for duplicate types 261 // (quadratic algorithm, but type switches tend to be reasonably small) 262 for t, pos := range seen { 263 if T == nil && t == nil || T != nil && t != nil && Identical(T, t) { 264 // talk about "case" rather than "type" because of nil case 265 Ts := "nil" 266 if T != nil { 267 Ts = T.String() 268 } 269 check.errorf(e.Pos(), "duplicate case %s in type switch", Ts) 270 check.error(pos, "\tprevious case") // secondary error, \t indented 271 continue L 272 } 273 } 274 seen[T] = e.Pos() 275 if T != nil { 276 check.typeAssertion(e.Pos(), x, xtyp, T) 277 } 278 } 279 return 280 } 281 282 // stmt typechecks statement s. 283 func (check *Checker) stmt(ctxt stmtContext, s ast.Stmt) { 284 // statements cannot use iota in general 285 // (constant declarations set it explicitly) 286 assert(check.iota == nil) 287 288 // statements must end with the same top scope as they started with 289 if debug { 290 defer func(scope *Scope) { 291 // don't check if code is panicking 292 if p := recover(); p != nil { 293 panic(p) 294 } 295 assert(scope == check.scope) 296 }(check.scope) 297 } 298 299 inner := ctxt &^ (fallthroughOk | finalSwitchCase) 300 switch s := s.(type) { 301 case *ast.BadStmt, *ast.EmptyStmt: 302 // ignore 303 304 case *ast.DeclStmt: 305 check.declStmt(s.Decl) 306 307 case *ast.LabeledStmt: 308 check.hasLabel = true 309 check.stmt(ctxt, s.Stmt) 310 311 case *ast.ExprStmt: 312 // spec: "With the exception of specific built-in functions, 313 // function and method calls and receive operations can appear 314 // in statement context. Such statements may be parenthesized." 315 var x operand 316 kind := check.rawExpr(&x, s.X, nil) 317 var msg string 318 switch x.mode { 319 default: 320 if kind == statement { 321 return 322 } 323 msg = "is not used" 324 case builtin: 325 msg = "must be called" 326 case typexpr: 327 msg = "is not an expression" 328 } 329 check.errorf(x.pos(), "%s %s", &x, msg) 330 331 case *ast.SendStmt: 332 var ch, x operand 333 check.expr(&ch, s.Chan) 334 check.expr(&x, s.Value) 335 if ch.mode == invalid || x.mode == invalid { 336 return 337 } 338 339 tch, ok := ch.typ.Underlying().(*Chan) 340 if !ok { 341 check.invalidOp(s.Arrow, "cannot send to non-chan type %s", ch.typ) 342 return 343 } 344 345 if tch.dir == RecvOnly { 346 check.invalidOp(s.Arrow, "cannot send to receive-only type %s", tch) 347 return 348 } 349 350 check.assignment(&x, tch.elem, "send") 351 352 case *ast.IncDecStmt: 353 var op token.Token 354 switch s.Tok { 355 case token.INC: 356 op = token.ADD 357 case token.DEC: 358 op = token.SUB 359 default: 360 check.invalidAST(s.TokPos, "unknown inc/dec operation %s", s.Tok) 361 return 362 } 363 364 var x operand 365 check.expr(&x, s.X) 366 if x.mode == invalid { 367 return 368 } 369 if !isNumeric(x.typ) { 370 check.invalidOp(s.X.Pos(), "%s%s (non-numeric type %s)", s.X, s.Tok, x.typ) 371 return 372 } 373 374 Y := &ast.BasicLit{ValuePos: s.X.Pos(), Kind: token.INT, Value: "1"} // use x's position 375 check.binary(&x, nil, s.X, Y, op) 376 if x.mode == invalid { 377 return 378 } 379 check.assignVar(s.X, &x) 380 381 case *ast.AssignStmt: 382 switch s.Tok { 383 case token.ASSIGN, token.DEFINE: 384 if len(s.Lhs) == 0 { 385 check.invalidAST(s.Pos(), "missing lhs in assignment") 386 return 387 } 388 if s.Tok == token.DEFINE { 389 check.shortVarDecl(s.TokPos, s.Lhs, s.Rhs) 390 } else { 391 // regular assignment 392 check.assignVars(s.Lhs, s.Rhs) 393 } 394 395 default: 396 // assignment operations 397 if len(s.Lhs) != 1 || len(s.Rhs) != 1 { 398 check.errorf(s.TokPos, "assignment operation %s requires single-valued expressions", s.Tok) 399 return 400 } 401 op := assignOp(s.Tok) 402 if op == token.ILLEGAL { 403 check.invalidAST(s.TokPos, "unknown assignment operation %s", s.Tok) 404 return 405 } 406 var x operand 407 check.binary(&x, nil, s.Lhs[0], s.Rhs[0], op) 408 if x.mode == invalid { 409 return 410 } 411 check.assignVar(s.Lhs[0], &x) 412 } 413 414 case *ast.GoStmt: 415 check.suspendedCall("go", s.Call) 416 417 case *ast.DeferStmt: 418 check.suspendedCall("defer", s.Call) 419 420 case *ast.ReturnStmt: 421 res := check.sig.results 422 if res.Len() > 0 { 423 // function returns results 424 // (if one, say the first, result parameter is named, all of them are named) 425 if len(s.Results) == 0 && res.vars[0].name != "" { 426 // spec: "Implementation restriction: A compiler may disallow an empty expression 427 // list in a "return" statement if a different entity (constant, type, or variable) 428 // with the same name as a result parameter is in scope at the place of the return." 429 for _, obj := range res.vars { 430 if _, alt := check.scope.LookupParent(obj.name, check.pos); alt != nil && alt != obj { 431 check.errorf(s.Pos(), "result parameter %s not in scope at return", obj.name) 432 check.errorf(alt.Pos(), "\tinner declaration of %s", obj) 433 // ok to continue 434 } 435 } 436 } else { 437 // return has results or result parameters are unnamed 438 check.initVars(res.vars, s.Results, s.Return) 439 } 440 } else if len(s.Results) > 0 { 441 check.error(s.Results[0].Pos(), "no result values expected") 442 check.use(s.Results...) 443 } 444 445 case *ast.BranchStmt: 446 if s.Label != nil { 447 check.hasLabel = true 448 return // checked in 2nd pass (check.labels) 449 } 450 switch s.Tok { 451 case token.BREAK: 452 if ctxt&breakOk == 0 { 453 check.error(s.Pos(), "break not in for, switch, or select statement") 454 } 455 case token.CONTINUE: 456 if ctxt&continueOk == 0 { 457 check.error(s.Pos(), "continue not in for statement") 458 } 459 case token.FALLTHROUGH: 460 if ctxt&fallthroughOk == 0 { 461 msg := "fallthrough statement out of place" 462 if ctxt&finalSwitchCase != 0 { 463 msg = "cannot fallthrough final case in switch" 464 } 465 check.error(s.Pos(), msg) 466 } 467 default: 468 check.invalidAST(s.Pos(), "branch statement: %s", s.Tok) 469 } 470 471 case *ast.BlockStmt: 472 check.openScope(s, "block") 473 defer check.closeScope() 474 475 check.stmtList(inner, s.List) 476 477 case *ast.IfStmt: 478 check.openScope(s, "if") 479 defer check.closeScope() 480 481 check.simpleStmt(s.Init) 482 var x operand 483 check.expr(&x, s.Cond) 484 if x.mode != invalid && !isBoolean(x.typ) { 485 check.error(s.Cond.Pos(), "non-boolean condition in if statement") 486 } 487 check.stmt(inner, s.Body) 488 // The parser produces a correct AST but if it was modified 489 // elsewhere the else branch may be invalid. Check again. 490 switch s.Else.(type) { 491 case nil, *ast.BadStmt: 492 // valid or error already reported 493 case *ast.IfStmt, *ast.BlockStmt: 494 check.stmt(inner, s.Else) 495 default: 496 check.error(s.Else.Pos(), "invalid else branch in if statement") 497 } 498 499 case *ast.SwitchStmt: 500 inner |= breakOk 501 check.openScope(s, "switch") 502 defer check.closeScope() 503 504 check.simpleStmt(s.Init) 505 var x operand 506 if s.Tag != nil { 507 check.expr(&x, s.Tag) 508 // By checking assignment of x to an invisible temporary 509 // (as a compiler would), we get all the relevant checks. 510 check.assignment(&x, nil, "switch expression") 511 } else { 512 // spec: "A missing switch expression is 513 // equivalent to the boolean value true." 514 x.mode = constant_ 515 x.typ = Typ[Bool] 516 x.val = constant.MakeBool(true) 517 x.expr = &ast.Ident{NamePos: s.Body.Lbrace, Name: "true"} 518 } 519 520 check.multipleDefaults(s.Body.List) 521 522 seen := make(valueMap) // map of seen case values to positions and types 523 for i, c := range s.Body.List { 524 clause, _ := c.(*ast.CaseClause) 525 if clause == nil { 526 check.invalidAST(c.Pos(), "incorrect expression switch case") 527 continue 528 } 529 check.caseValues(&x, clause.List, seen) 530 check.openScope(clause, "case") 531 inner := inner 532 if i+1 < len(s.Body.List) { 533 inner |= fallthroughOk 534 } else { 535 inner |= finalSwitchCase 536 } 537 check.stmtList(inner, clause.Body) 538 check.closeScope() 539 } 540 541 case *ast.TypeSwitchStmt: 542 inner |= breakOk 543 check.openScope(s, "type switch") 544 defer check.closeScope() 545 546 check.simpleStmt(s.Init) 547 548 // A type switch guard must be of the form: 549 // 550 // TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" . 551 // 552 // The parser is checking syntactic correctness; 553 // remaining syntactic errors are considered AST errors here. 554 // TODO(gri) better factoring of error handling (invalid ASTs) 555 // 556 var lhs *ast.Ident // lhs identifier or nil 557 var rhs ast.Expr 558 switch guard := s.Assign.(type) { 559 case *ast.ExprStmt: 560 rhs = guard.X 561 case *ast.AssignStmt: 562 if len(guard.Lhs) != 1 || guard.Tok != token.DEFINE || len(guard.Rhs) != 1 { 563 check.invalidAST(s.Pos(), "incorrect form of type switch guard") 564 return 565 } 566 567 lhs, _ = guard.Lhs[0].(*ast.Ident) 568 if lhs == nil { 569 check.invalidAST(s.Pos(), "incorrect form of type switch guard") 570 return 571 } 572 573 if lhs.Name == "_" { 574 // _ := x.(type) is an invalid short variable declaration 575 check.softErrorf(lhs.Pos(), "no new variable on left side of :=") 576 lhs = nil // avoid declared but not used error below 577 } else { 578 check.recordDef(lhs, nil) // lhs variable is implicitly declared in each cause clause 579 } 580 581 rhs = guard.Rhs[0] 582 583 default: 584 check.invalidAST(s.Pos(), "incorrect form of type switch guard") 585 return 586 } 587 588 // rhs must be of the form: expr.(type) and expr must be an interface 589 expr, _ := rhs.(*ast.TypeAssertExpr) 590 if expr == nil || expr.Type != nil { 591 check.invalidAST(s.Pos(), "incorrect form of type switch guard") 592 return 593 } 594 var x operand 595 check.expr(&x, expr.X) 596 if x.mode == invalid { 597 return 598 } 599 xtyp, _ := x.typ.Underlying().(*Interface) 600 if xtyp == nil { 601 check.errorf(x.pos(), "%s is not an interface", &x) 602 return 603 } 604 605 check.multipleDefaults(s.Body.List) 606 607 var lhsVars []*Var // list of implicitly declared lhs variables 608 seen := make(map[Type]token.Pos) // map of seen types to positions 609 for _, s := range s.Body.List { 610 clause, _ := s.(*ast.CaseClause) 611 if clause == nil { 612 check.invalidAST(s.Pos(), "incorrect type switch case") 613 continue 614 } 615 // Check each type in this type switch case. 616 T := check.caseTypes(&x, xtyp, clause.List, seen) 617 check.openScope(clause, "case") 618 // If lhs exists, declare a corresponding variable in the case-local scope. 619 if lhs != nil { 620 // spec: "The TypeSwitchGuard may include a short variable declaration. 621 // When that form is used, the variable is declared at the beginning of 622 // the implicit block in each clause. In clauses with a case listing 623 // exactly one type, the variable has that type; otherwise, the variable 624 // has the type of the expression in the TypeSwitchGuard." 625 if len(clause.List) != 1 || T == nil { 626 T = x.typ 627 } 628 obj := NewVar(lhs.Pos(), check.pkg, lhs.Name, T) 629 scopePos := clause.Pos() + token.Pos(len("default")) // for default clause (len(List) == 0) 630 if n := len(clause.List); n > 0 { 631 scopePos = clause.List[n-1].End() 632 } 633 check.declare(check.scope, nil, obj, scopePos) 634 check.recordImplicit(clause, obj) 635 // For the "declared but not used" error, all lhs variables act as 636 // one; i.e., if any one of them is 'used', all of them are 'used'. 637 // Collect them for later analysis. 638 lhsVars = append(lhsVars, obj) 639 } 640 check.stmtList(inner, clause.Body) 641 check.closeScope() 642 } 643 644 // If lhs exists, we must have at least one lhs variable that was used. 645 if lhs != nil { 646 var used bool 647 for _, v := range lhsVars { 648 if v.used { 649 used = true 650 } 651 v.used = true // avoid usage error when checking entire function 652 } 653 if !used { 654 check.softErrorf(lhs.Pos(), "%s declared but not used", lhs.Name) 655 } 656 } 657 658 case *ast.SelectStmt: 659 inner |= breakOk 660 661 check.multipleDefaults(s.Body.List) 662 663 for _, s := range s.Body.List { 664 clause, _ := s.(*ast.CommClause) 665 if clause == nil { 666 continue // error reported before 667 } 668 669 // clause.Comm must be a SendStmt, RecvStmt, or default case 670 valid := false 671 var rhs ast.Expr // rhs of RecvStmt, or nil 672 switch s := clause.Comm.(type) { 673 case nil, *ast.SendStmt: 674 valid = true 675 case *ast.AssignStmt: 676 if len(s.Rhs) == 1 { 677 rhs = s.Rhs[0] 678 } 679 case *ast.ExprStmt: 680 rhs = s.X 681 } 682 683 // if present, rhs must be a receive operation 684 if rhs != nil { 685 if x, _ := unparen(rhs).(*ast.UnaryExpr); x != nil && x.Op == token.ARROW { 686 valid = true 687 } 688 } 689 690 if !valid { 691 check.error(clause.Comm.Pos(), "select case must be send or receive (possibly with assignment)") 692 continue 693 } 694 695 check.openScope(s, "case") 696 if clause.Comm != nil { 697 check.stmt(inner, clause.Comm) 698 } 699 check.stmtList(inner, clause.Body) 700 check.closeScope() 701 } 702 703 case *ast.ForStmt: 704 inner |= breakOk | continueOk 705 check.openScope(s, "for") 706 defer check.closeScope() 707 708 check.simpleStmt(s.Init) 709 if s.Cond != nil { 710 var x operand 711 check.expr(&x, s.Cond) 712 if x.mode != invalid && !isBoolean(x.typ) { 713 check.error(s.Cond.Pos(), "non-boolean condition in for statement") 714 } 715 } 716 check.simpleStmt(s.Post) 717 // spec: "The init statement may be a short variable 718 // declaration, but the post statement must not." 719 if s, _ := s.Post.(*ast.AssignStmt); s != nil && s.Tok == token.DEFINE { 720 check.softErrorf(s.Pos(), "cannot declare in post statement") 721 check.use(s.Lhs...) // avoid follow-up errors 722 } 723 check.stmt(inner, s.Body) 724 725 case *ast.RangeStmt: 726 inner |= breakOk | continueOk 727 check.openScope(s, "for") 728 defer check.closeScope() 729 730 // check expression to iterate over 731 var x operand 732 check.expr(&x, s.X) 733 734 // determine key/value types 735 var key, val Type 736 if x.mode != invalid { 737 switch typ := x.typ.Underlying().(type) { 738 case *Basic: 739 if isString(typ) { 740 key = Typ[Int] 741 val = universeRune // use 'rune' name 742 } 743 case *Array: 744 key = Typ[Int] 745 val = typ.elem 746 case *Slice: 747 key = Typ[Int] 748 val = typ.elem 749 case *Pointer: 750 if typ, _ := typ.base.Underlying().(*Array); typ != nil { 751 key = Typ[Int] 752 val = typ.elem 753 } 754 case *Map: 755 key = typ.key 756 val = typ.elem 757 case *Chan: 758 key = typ.elem 759 val = Typ[Invalid] 760 if typ.dir == SendOnly { 761 check.errorf(x.pos(), "cannot range over send-only channel %s", &x) 762 // ok to continue 763 } 764 if s.Value != nil { 765 check.errorf(s.Value.Pos(), "iteration over %s permits only one iteration variable", &x) 766 // ok to continue 767 } 768 } 769 } 770 771 if key == nil { 772 check.errorf(x.pos(), "cannot range over %s", &x) 773 // ok to continue 774 } 775 776 // check assignment to/declaration of iteration variables 777 // (irregular assignment, cannot easily map to existing assignment checks) 778 779 // lhs expressions and initialization value (rhs) types 780 lhs := [2]ast.Expr{s.Key, s.Value} 781 rhs := [2]Type{key, val} // key, val may be nil 782 783 if s.Tok == token.DEFINE { 784 // short variable declaration; variable scope starts after the range clause 785 // (the for loop opens a new scope, so variables on the lhs never redeclare 786 // previously declared variables) 787 var vars []*Var 788 for i, lhs := range lhs { 789 if lhs == nil { 790 continue 791 } 792 793 // determine lhs variable 794 var obj *Var 795 if ident, _ := lhs.(*ast.Ident); ident != nil { 796 // declare new variable 797 name := ident.Name 798 obj = NewVar(ident.Pos(), check.pkg, name, nil) 799 check.recordDef(ident, obj) 800 // _ variables don't count as new variables 801 if name != "_" { 802 vars = append(vars, obj) 803 } 804 } else { 805 check.errorf(lhs.Pos(), "cannot declare %s", lhs) 806 obj = NewVar(lhs.Pos(), check.pkg, "_", nil) // dummy variable 807 } 808 809 // initialize lhs variable 810 if typ := rhs[i]; typ != nil { 811 x.mode = value 812 x.expr = lhs // we don't have a better rhs expression to use here 813 x.typ = typ 814 check.initVar(obj, &x, "range clause") 815 } else { 816 obj.typ = Typ[Invalid] 817 obj.used = true // don't complain about unused variable 818 } 819 } 820 821 // declare variables 822 if len(vars) > 0 { 823 scopePos := s.X.End() 824 for _, obj := range vars { 825 // spec: "The scope of a constant or variable identifier declared inside 826 // a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl 827 // for short variable declarations) and ends at the end of the innermost 828 // containing block." 829 check.declare(check.scope, nil /* recordDef already called */, obj, scopePos) 830 } 831 } else { 832 check.error(s.TokPos, "no new variables on left side of :=") 833 } 834 } else { 835 // ordinary assignment 836 for i, lhs := range lhs { 837 if lhs == nil { 838 continue 839 } 840 if typ := rhs[i]; typ != nil { 841 x.mode = value 842 x.expr = lhs // we don't have a better rhs expression to use here 843 x.typ = typ 844 check.assignVar(lhs, &x) 845 } 846 } 847 } 848 849 check.stmt(inner, s.Body) 850 851 default: 852 check.error(s.Pos(), "invalid statement") 853 } 854 }