github.com/zxy12/golang151_with_comment@v0.0.0-20190507085033-721809559d3c/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 func (check *Checker) caseValues(x operand /* copy argument (not *operand!) */, values []ast.Expr) { 159 // No duplicate checking for now. See issue 4524. 160 for _, e := range values { 161 var y operand 162 check.expr(&y, e) 163 if y.mode == invalid { 164 return 165 } 166 // TODO(gri) The convertUntyped call pair below appears in other places. Factor! 167 // Order matters: By comparing y against x, error positions are at the case values. 168 check.convertUntyped(&y, x.typ) 169 if y.mode == invalid { 170 return 171 } 172 check.convertUntyped(&x, y.typ) 173 if x.mode == invalid { 174 return 175 } 176 check.comparison(&y, &x, token.EQL) 177 } 178 } 179 180 func (check *Checker) caseTypes(x *operand, xtyp *Interface, types []ast.Expr, seen map[Type]token.Pos) (T Type) { 181 L: 182 for _, e := range types { 183 T = check.typOrNil(e) 184 if T == Typ[Invalid] { 185 continue 186 } 187 // complain about duplicate types 188 // TODO(gri) use a type hash to avoid quadratic algorithm 189 for t, pos := range seen { 190 if T == nil && t == nil || T != nil && t != nil && Identical(T, t) { 191 // talk about "case" rather than "type" because of nil case 192 check.error(e.Pos(), "duplicate case in type switch") 193 check.errorf(pos, "\tprevious case %s", T) // secondary error, \t indented 194 continue L 195 } 196 } 197 seen[T] = e.Pos() 198 if T != nil { 199 check.typeAssertion(e.Pos(), x, xtyp, T) 200 } 201 } 202 return 203 } 204 205 // stmt typechecks statement s. 206 func (check *Checker) stmt(ctxt stmtContext, s ast.Stmt) { 207 // statements cannot use iota in general 208 // (constant declarations set it explicitly) 209 assert(check.iota == nil) 210 211 // statements must end with the same top scope as they started with 212 if debug { 213 defer func(scope *Scope) { 214 // don't check if code is panicking 215 if p := recover(); p != nil { 216 panic(p) 217 } 218 assert(scope == check.scope) 219 }(check.scope) 220 } 221 222 inner := ctxt &^ fallthroughOk 223 switch s := s.(type) { 224 case *ast.BadStmt, *ast.EmptyStmt: 225 // ignore 226 227 case *ast.DeclStmt: 228 check.declStmt(s.Decl) 229 230 case *ast.LabeledStmt: 231 check.hasLabel = true 232 check.stmt(ctxt, s.Stmt) 233 234 case *ast.ExprStmt: 235 // spec: "With the exception of specific built-in functions, 236 // function and method calls and receive operations can appear 237 // in statement context. Such statements may be parenthesized." 238 var x operand 239 kind := check.rawExpr(&x, s.X, nil) 240 var msg string 241 switch x.mode { 242 default: 243 if kind == statement { 244 return 245 } 246 msg = "is not used" 247 case builtin: 248 msg = "must be called" 249 case typexpr: 250 msg = "is not an expression" 251 } 252 check.errorf(x.pos(), "%s %s", &x, msg) 253 254 case *ast.SendStmt: 255 var ch, x operand 256 check.expr(&ch, s.Chan) 257 check.expr(&x, s.Value) 258 if ch.mode == invalid || x.mode == invalid { 259 return 260 } 261 if tch, ok := ch.typ.Underlying().(*Chan); !ok || tch.dir == RecvOnly || !check.assignment(&x, tch.elem) { 262 if x.mode != invalid { 263 check.invalidOp(ch.pos(), "cannot send %s to channel %s", &x, &ch) 264 } 265 } 266 267 case *ast.IncDecStmt: 268 var op token.Token 269 switch s.Tok { 270 case token.INC: 271 op = token.ADD 272 case token.DEC: 273 op = token.SUB 274 default: 275 check.invalidAST(s.TokPos, "unknown inc/dec operation %s", s.Tok) 276 return 277 } 278 var x operand 279 Y := &ast.BasicLit{ValuePos: s.X.Pos(), Kind: token.INT, Value: "1"} // use x's position 280 check.binary(&x, nil, s.X, Y, op) 281 if x.mode == invalid { 282 return 283 } 284 check.assignVar(s.X, &x) 285 286 case *ast.AssignStmt: 287 switch s.Tok { 288 case token.ASSIGN, token.DEFINE: 289 if len(s.Lhs) == 0 { 290 check.invalidAST(s.Pos(), "missing lhs in assignment") 291 return 292 } 293 if s.Tok == token.DEFINE { 294 check.shortVarDecl(s.TokPos, s.Lhs, s.Rhs) 295 } else { 296 // regular assignment 297 check.assignVars(s.Lhs, s.Rhs) 298 } 299 300 default: 301 // assignment operations 302 if len(s.Lhs) != 1 || len(s.Rhs) != 1 { 303 check.errorf(s.TokPos, "assignment operation %s requires single-valued expressions", s.Tok) 304 return 305 } 306 op := assignOp(s.Tok) 307 if op == token.ILLEGAL { 308 check.invalidAST(s.TokPos, "unknown assignment operation %s", s.Tok) 309 return 310 } 311 var x operand 312 check.binary(&x, nil, s.Lhs[0], s.Rhs[0], op) 313 if x.mode == invalid { 314 return 315 } 316 check.assignVar(s.Lhs[0], &x) 317 } 318 319 case *ast.GoStmt: 320 check.suspendedCall("go", s.Call) 321 322 case *ast.DeferStmt: 323 check.suspendedCall("defer", s.Call) 324 325 case *ast.ReturnStmt: 326 res := check.sig.results 327 if res.Len() > 0 { 328 // function returns results 329 // (if one, say the first, result parameter is named, all of them are named) 330 if len(s.Results) == 0 && res.vars[0].name != "" { 331 // spec: "Implementation restriction: A compiler may disallow an empty expression 332 // list in a "return" statement if a different entity (constant, type, or variable) 333 // with the same name as a result parameter is in scope at the place of the return." 334 for _, obj := range res.vars { 335 if _, alt := check.scope.LookupParent(obj.name, check.pos); alt != nil && alt != obj { 336 check.errorf(s.Pos(), "result parameter %s not in scope at return", obj.name) 337 check.errorf(alt.Pos(), "\tinner declaration of %s", obj) 338 // ok to continue 339 } 340 } 341 } else { 342 // return has results or result parameters are unnamed 343 check.initVars(res.vars, s.Results, s.Return) 344 } 345 } else if len(s.Results) > 0 { 346 check.error(s.Results[0].Pos(), "no result values expected") 347 check.use(s.Results...) 348 } 349 350 case *ast.BranchStmt: 351 if s.Label != nil { 352 check.hasLabel = true 353 return // checked in 2nd pass (check.labels) 354 } 355 switch s.Tok { 356 case token.BREAK: 357 if ctxt&breakOk == 0 { 358 check.error(s.Pos(), "break not in for, switch, or select statement") 359 } 360 case token.CONTINUE: 361 if ctxt&continueOk == 0 { 362 check.error(s.Pos(), "continue not in for statement") 363 } 364 case token.FALLTHROUGH: 365 if ctxt&fallthroughOk == 0 { 366 check.error(s.Pos(), "fallthrough statement out of place") 367 } 368 default: 369 check.invalidAST(s.Pos(), "branch statement: %s", s.Tok) 370 } 371 372 case *ast.BlockStmt: 373 check.openScope(s, "block") 374 defer check.closeScope() 375 376 check.stmtList(inner, s.List) 377 378 case *ast.IfStmt: 379 check.openScope(s, "if") 380 defer check.closeScope() 381 382 check.simpleStmt(s.Init) 383 var x operand 384 check.expr(&x, s.Cond) 385 if x.mode != invalid && !isBoolean(x.typ) { 386 check.error(s.Cond.Pos(), "non-boolean condition in if statement") 387 } 388 check.stmt(inner, s.Body) 389 if s.Else != nil { 390 check.stmt(inner, s.Else) 391 } 392 393 case *ast.SwitchStmt: 394 inner |= breakOk 395 check.openScope(s, "switch") 396 defer check.closeScope() 397 398 check.simpleStmt(s.Init) 399 var x operand 400 if s.Tag != nil { 401 check.expr(&x, s.Tag) 402 } else { 403 // spec: "A missing switch expression is 404 // equivalent to the boolean value true." 405 x.mode = constant_ 406 x.typ = Typ[Bool] 407 x.val = constant.MakeBool(true) 408 x.expr = &ast.Ident{NamePos: s.Body.Lbrace, Name: "true"} 409 } 410 411 check.multipleDefaults(s.Body.List) 412 413 for i, c := range s.Body.List { 414 clause, _ := c.(*ast.CaseClause) 415 if clause == nil { 416 check.invalidAST(c.Pos(), "incorrect expression switch case") 417 continue 418 } 419 if x.mode != invalid { 420 check.caseValues(x, clause.List) 421 } 422 check.openScope(clause, "case") 423 inner := inner 424 if i+1 < len(s.Body.List) { 425 inner |= fallthroughOk 426 } 427 check.stmtList(inner, clause.Body) 428 check.closeScope() 429 } 430 431 case *ast.TypeSwitchStmt: 432 inner |= breakOk 433 check.openScope(s, "type switch") 434 defer check.closeScope() 435 436 check.simpleStmt(s.Init) 437 438 // A type switch guard must be of the form: 439 // 440 // TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" . 441 // 442 // The parser is checking syntactic correctness; 443 // remaining syntactic errors are considered AST errors here. 444 // TODO(gri) better factoring of error handling (invalid ASTs) 445 // 446 var lhs *ast.Ident // lhs identifier or nil 447 var rhs ast.Expr 448 switch guard := s.Assign.(type) { 449 case *ast.ExprStmt: 450 rhs = guard.X 451 case *ast.AssignStmt: 452 if len(guard.Lhs) != 1 || guard.Tok != token.DEFINE || len(guard.Rhs) != 1 { 453 check.invalidAST(s.Pos(), "incorrect form of type switch guard") 454 return 455 } 456 457 lhs, _ = guard.Lhs[0].(*ast.Ident) 458 if lhs == nil { 459 check.invalidAST(s.Pos(), "incorrect form of type switch guard") 460 return 461 } 462 463 if lhs.Name == "_" { 464 // _ := x.(type) is an invalid short variable declaration 465 check.softErrorf(lhs.Pos(), "no new variable on left side of :=") 466 lhs = nil // avoid declared but not used error below 467 } else { 468 check.recordDef(lhs, nil) // lhs variable is implicitly declared in each cause clause 469 } 470 471 rhs = guard.Rhs[0] 472 473 default: 474 check.invalidAST(s.Pos(), "incorrect form of type switch guard") 475 return 476 } 477 478 // rhs must be of the form: expr.(type) and expr must be an interface 479 expr, _ := rhs.(*ast.TypeAssertExpr) 480 if expr == nil || expr.Type != nil { 481 check.invalidAST(s.Pos(), "incorrect form of type switch guard") 482 return 483 } 484 var x operand 485 check.expr(&x, expr.X) 486 if x.mode == invalid { 487 return 488 } 489 xtyp, _ := x.typ.Underlying().(*Interface) 490 if xtyp == nil { 491 check.errorf(x.pos(), "%s is not an interface", &x) 492 return 493 } 494 495 check.multipleDefaults(s.Body.List) 496 497 var lhsVars []*Var // list of implicitly declared lhs variables 498 seen := make(map[Type]token.Pos) // map of seen types to positions 499 for _, s := range s.Body.List { 500 clause, _ := s.(*ast.CaseClause) 501 if clause == nil { 502 check.invalidAST(s.Pos(), "incorrect type switch case") 503 continue 504 } 505 // Check each type in this type switch case. 506 T := check.caseTypes(&x, xtyp, clause.List, seen) 507 check.openScope(clause, "case") 508 // If lhs exists, declare a corresponding variable in the case-local scope. 509 if lhs != nil { 510 // spec: "The TypeSwitchGuard may include a short variable declaration. 511 // When that form is used, the variable is declared at the beginning of 512 // the implicit block in each clause. In clauses with a case listing 513 // exactly one type, the variable has that type; otherwise, the variable 514 // has the type of the expression in the TypeSwitchGuard." 515 if len(clause.List) != 1 || T == nil { 516 T = x.typ 517 } 518 obj := NewVar(lhs.Pos(), check.pkg, lhs.Name, T) 519 scopePos := clause.End() 520 if len(clause.Body) > 0 { 521 scopePos = clause.Body[0].Pos() 522 } 523 check.declare(check.scope, nil, obj, scopePos) 524 check.recordImplicit(clause, obj) 525 // For the "declared but not used" error, all lhs variables act as 526 // one; i.e., if any one of them is 'used', all of them are 'used'. 527 // Collect them for later analysis. 528 lhsVars = append(lhsVars, obj) 529 } 530 check.stmtList(inner, clause.Body) 531 check.closeScope() 532 } 533 534 // If lhs exists, we must have at least one lhs variable that was used. 535 if lhs != nil { 536 var used bool 537 for _, v := range lhsVars { 538 if v.used { 539 used = true 540 } 541 v.used = true // avoid usage error when checking entire function 542 } 543 if !used { 544 check.softErrorf(lhs.Pos(), "%s declared but not used", lhs.Name) 545 } 546 } 547 548 case *ast.SelectStmt: 549 inner |= breakOk 550 551 check.multipleDefaults(s.Body.List) 552 553 for _, s := range s.Body.List { 554 clause, _ := s.(*ast.CommClause) 555 if clause == nil { 556 continue // error reported before 557 } 558 559 // clause.Comm must be a SendStmt, RecvStmt, or default case 560 valid := false 561 var rhs ast.Expr // rhs of RecvStmt, or nil 562 switch s := clause.Comm.(type) { 563 case nil, *ast.SendStmt: 564 valid = true 565 case *ast.AssignStmt: 566 if len(s.Rhs) == 1 { 567 rhs = s.Rhs[0] 568 } 569 case *ast.ExprStmt: 570 rhs = s.X 571 } 572 573 // if present, rhs must be a receive operation 574 if rhs != nil { 575 if x, _ := unparen(rhs).(*ast.UnaryExpr); x != nil && x.Op == token.ARROW { 576 valid = true 577 } 578 } 579 580 if !valid { 581 check.error(clause.Comm.Pos(), "select case must be send or receive (possibly with assignment)") 582 continue 583 } 584 585 check.openScope(s, "case") 586 if clause.Comm != nil { 587 check.stmt(inner, clause.Comm) 588 } 589 check.stmtList(inner, clause.Body) 590 check.closeScope() 591 } 592 593 case *ast.ForStmt: 594 inner |= breakOk | continueOk 595 check.openScope(s, "for") 596 defer check.closeScope() 597 598 check.simpleStmt(s.Init) 599 if s.Cond != nil { 600 var x operand 601 check.expr(&x, s.Cond) 602 if x.mode != invalid && !isBoolean(x.typ) { 603 check.error(s.Cond.Pos(), "non-boolean condition in for statement") 604 } 605 } 606 check.simpleStmt(s.Post) 607 // spec: "The init statement may be a short variable 608 // declaration, but the post statement must not." 609 if s, _ := s.Post.(*ast.AssignStmt); s != nil && s.Tok == token.DEFINE { 610 check.softErrorf(s.Pos(), "cannot declare in post statement") 611 check.use(s.Lhs...) // avoid follow-up errors 612 } 613 check.stmt(inner, s.Body) 614 615 case *ast.RangeStmt: 616 inner |= breakOk | continueOk 617 check.openScope(s, "for") 618 defer check.closeScope() 619 620 // check expression to iterate over 621 var x operand 622 check.expr(&x, s.X) 623 624 // determine key/value types 625 var key, val Type 626 if x.mode != invalid { 627 switch typ := x.typ.Underlying().(type) { 628 case *Basic: 629 if isString(typ) { 630 key = Typ[Int] 631 val = universeRune // use 'rune' name 632 } 633 case *Array: 634 key = Typ[Int] 635 val = typ.elem 636 case *Slice: 637 key = Typ[Int] 638 val = typ.elem 639 case *Pointer: 640 if typ, _ := typ.base.Underlying().(*Array); typ != nil { 641 key = Typ[Int] 642 val = typ.elem 643 } 644 case *Map: 645 key = typ.key 646 val = typ.elem 647 case *Chan: 648 key = typ.elem 649 val = Typ[Invalid] 650 if typ.dir == SendOnly { 651 check.errorf(x.pos(), "cannot range over send-only channel %s", &x) 652 // ok to continue 653 } 654 if s.Value != nil { 655 check.errorf(s.Value.Pos(), "iteration over %s permits only one iteration variable", &x) 656 // ok to continue 657 } 658 } 659 } 660 661 if key == nil { 662 check.errorf(x.pos(), "cannot range over %s", &x) 663 // ok to continue 664 } 665 666 // check assignment to/declaration of iteration variables 667 // (irregular assignment, cannot easily map to existing assignment checks) 668 669 // lhs expressions and initialization value (rhs) types 670 lhs := [2]ast.Expr{s.Key, s.Value} 671 rhs := [2]Type{key, val} // key, val may be nil 672 673 if s.Tok == token.DEFINE { 674 // short variable declaration; variable scope starts after the range clause 675 // (the for loop opens a new scope, so variables on the lhs never redeclare 676 // previously declared variables) 677 var vars []*Var 678 for i, lhs := range lhs { 679 if lhs == nil { 680 continue 681 } 682 683 // determine lhs variable 684 var obj *Var 685 if ident, _ := lhs.(*ast.Ident); ident != nil { 686 // declare new variable 687 name := ident.Name 688 obj = NewVar(ident.Pos(), check.pkg, name, nil) 689 check.recordDef(ident, obj) 690 // _ variables don't count as new variables 691 if name != "_" { 692 vars = append(vars, obj) 693 } 694 } else { 695 check.errorf(lhs.Pos(), "cannot declare %s", lhs) 696 obj = NewVar(lhs.Pos(), check.pkg, "_", nil) // dummy variable 697 } 698 699 // initialize lhs variable 700 if typ := rhs[i]; typ != nil { 701 x.mode = value 702 x.expr = lhs // we don't have a better rhs expression to use here 703 x.typ = typ 704 check.initVar(obj, &x, false) 705 } else { 706 obj.typ = Typ[Invalid] 707 obj.used = true // don't complain about unused variable 708 } 709 } 710 711 // declare variables 712 if len(vars) > 0 { 713 for _, obj := range vars { 714 // spec: "The scope of a constant or variable identifier declared inside 715 // a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl 716 // for short variable declarations) and ends at the end of the innermost 717 // containing block." 718 scopePos := s.End() 719 check.declare(check.scope, nil /* recordDef already called */, obj, scopePos) 720 } 721 } else { 722 check.error(s.TokPos, "no new variables on left side of :=") 723 } 724 } else { 725 // ordinary assignment 726 for i, lhs := range lhs { 727 if lhs == nil { 728 continue 729 } 730 if typ := rhs[i]; typ != nil { 731 x.mode = value 732 x.expr = lhs // we don't have a better rhs expression to use here 733 x.typ = typ 734 check.assignVar(lhs, &x) 735 } 736 } 737 } 738 739 check.stmt(inner, s.Body) 740 741 default: 742 check.error(s.Pos(), "invalid statement") 743 } 744 }