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