3 use rustc::hir::def::Def;
4 use rustc::hir::intravisit::{Visitor, walk_expr, walk_block, walk_decl};
5 use rustc::hir::map::Node::NodeBlock;
7 use rustc::middle::const_val::ConstVal;
8 use rustc::middle::region::CodeExtent;
10 use rustc_const_eval::EvalHint::ExprTypeChecked;
11 use rustc_const_eval::eval_const_expr_partial;
13 use std::collections::HashMap;
16 use utils::{snippet, span_lint, get_parent_expr, match_trait_method, match_type, in_external_macro,
17 span_help_and_lint, is_integer_literal, get_enclosing_block, span_lint_and_then, unsugar_range,
18 walk_ptrs_ty, recover_for_loop};
20 use utils::UnsugaredRange;
22 /// **What it does:** This lint checks for looping over the range of `0..len` of some collection just to get the values by index.
24 /// **Why is this bad?** Just iterating the collection itself makes the intent more clear and is probably faster.
26 /// **Known problems:** None
30 /// for i in 0..vec.len() {
31 /// println!("{}", vec[i]);
35 pub NEEDLESS_RANGE_LOOP,
37 "for-looping over a range of indices where an iterator over items would do"
40 /// **What it does:** This lint checks for loops on `x.iter()` where `&x` will do, and suggest the latter.
42 /// **Why is this bad?** Readability.
44 /// **Known problems:** False negatives. We currently only warn on some known types.
46 /// **Example:** `for x in y.iter() { .. }` (where y is a `Vec` or slice)
48 pub EXPLICIT_ITER_LOOP,
50 "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
53 /// **What it does:** This lint checks for loops on `x.next()`.
55 /// **Why is this bad?** `next()` returns either `Some(value)` if there was a value, or `None` otherwise. The insidious thing is that `Option<_>` implements `IntoIterator`, so that possibly one value will be iterated, leading to some hard to find bugs. No one will want to write such code [except to win an Underhanded Rust Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
57 /// **Known problems:** None
59 /// **Example:** `for x in y.next() { .. }`
63 "for-looping over `_.next()` which is probably not intended"
66 /// **What it does:** This lint checks for `for` loops over `Option` values.
68 /// **Why is this bad?** Readability. This is more clearly expressed as an `if let`.
70 /// **Known problems:** None
72 /// **Example:** `for x in option { .. }`. This should be `if let Some(x) = option { .. }`.
74 pub FOR_LOOP_OVER_OPTION,
76 "for-looping over an `Option`, which is more clearly expressed as an `if let`"
79 /// **What it does:** This lint checks for `for` loops over `Result` values.
81 /// **Why is this bad?** Readability. This is more clearly expressed as an `if let`.
83 /// **Known problems:** None
85 /// **Example:** `for x in result { .. }`. This should be `if let Ok(x) = result { .. }`.
87 pub FOR_LOOP_OVER_RESULT,
89 "for-looping over a `Result`, which is more clearly expressed as an `if let`"
92 /// **What it does:** This lint detects `loop + match` combinations that are easier written as a `while let` loop.
94 /// **Why is this bad?** The `while let` loop is usually shorter and more readable
96 /// **Known problems:** Sometimes the wrong binding is displayed (#383)
102 /// let x = match y {
106 /// // .. do something with x
108 /// // is easier written as
109 /// while let Some(x) = y {
110 /// // .. do something with x
116 "`loop { if let { ... } else break }` can be written as a `while let` loop"
119 /// **What it does:** This lint checks for using `collect()` on an iterator without using the result.
121 /// **Why is this bad?** It is more idiomatic to use a `for` loop over the iterator instead.
123 /// **Known problems:** None
125 /// **Example:** `vec.iter().map(|x| /* some operation returning () */).collect::<Vec<_>>();`
129 "`collect()`ing an iterator without using the result; this is usually better \
130 written as a for loop"
133 /// **What it does:** This lint checks for loops over ranges `x..y` where both `x` and `y` are constant and `x` is greater or equal to `y`, unless the range is reversed or has a negative `.step_by(_)`.
135 /// **Why is it bad?** Such loops will either be skipped or loop until wrap-around (in debug code, this may `panic!()`). Both options are probably not intended.
137 /// **Known problems:** The lint cannot catch loops over dynamically defined ranges. Doing this would require simulating all possible inputs and code paths through the program, which would be complex and error-prone.
139 /// **Examples**: `for x in 5..10-5 { .. }` (oops, stray `-`)
141 pub REVERSE_RANGE_LOOP,
143 "Iterating over an empty range, such as `10..0` or `5..5`"
146 /// **What it does:** This lint checks `for` loops over slices with an explicit counter and suggests the use of `.enumerate()`.
148 /// **Why is it bad?** Not only is the version using `.enumerate()` more readable, the compiler is able to remove bounds checks which can lead to faster code in some instances.
150 /// **Known problems:** None.
152 /// **Example:** `for i in 0..v.len() { foo(v[i]); }` or `for i in 0..v.len() { bar(i, v[i]); }`
154 pub EXPLICIT_COUNTER_LOOP,
156 "for-looping with an explicit counter when `_.enumerate()` would do"
159 /// **What it does:** This lint checks for empty `loop` expressions.
161 /// **Why is this bad?** Those busy loops burn CPU cycles without doing anything. Think of the environment and either block on something or at least make the thread sleep for some microseconds.
163 /// **Known problems:** None
165 /// **Example:** `loop {}`
169 "empty `loop {}` detected"
172 /// **What it does:** This lint checks for `while let` expressions on iterators.
174 /// **Why is this bad?** Readability. A simple `for` loop is shorter and conveys the intent better.
176 /// **Known problems:** None
178 /// **Example:** `while let Some(val) = iter() { .. }`
180 pub WHILE_LET_ON_ITERATOR,
182 "using a while-let loop instead of a for loop on an iterator"
185 /// **What it does:** This warns when you iterate on a map (`HashMap` or `BTreeMap`) and ignore
186 /// either the keys or values.
188 /// **Why is this bad?** Readability. There are `keys` and `values` methods that can be used to
189 /// express that don't need the values or keys.
191 /// **Known problems:** None
195 /// for (k, _) in &map { .. }
197 /// could be replaced by
199 /// for k in map.keys() { .. }
204 "looping on a map using `iter` when `keys` or `values` would do"
207 #[derive(Copy, Clone)]
208 pub struct LoopsPass;
210 impl LintPass for LoopsPass {
211 fn get_lints(&self) -> LintArray {
212 lint_array!(NEEDLESS_RANGE_LOOP,
218 EXPLICIT_COUNTER_LOOP,
220 WHILE_LET_ON_ITERATOR,
225 impl LateLintPass for LoopsPass {
226 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
227 if let Some((pat, arg, body)) = recover_for_loop(expr) {
228 check_for_loop(cx, pat, arg, body, expr);
230 // check for `loop { if let {} else break }` that could be `while let`
231 // (also matches an explicit "match" instead of "if let")
232 // (even if the "match" or "if let" is used for declaration)
233 if let ExprLoop(ref block, _) = expr.node {
234 // also check for empty `loop {}` statements
235 if block.stmts.is_empty() && block.expr.is_none() {
239 "empty `loop {}` detected. You may want to either use `panic!()` or add \
240 `std::thread::sleep(..);` to the loop body.");
243 // extract the expression from the first statement (if any) in a block
244 let inner_stmt_expr = extract_expr_from_first_stmt(block);
245 // or extract the first expression (if any) from the block
246 if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
247 if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node {
248 // ensure "if let" compatible match structure
250 MatchSource::Normal |
251 MatchSource::IfLetDesugar { .. } => {
252 if arms.len() == 2 &&
253 arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
254 arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
255 is_break_expr(&arms[1].body) {
256 if in_external_macro(cx, expr.span) {
260 // NOTE: we used to make build a body here instead of using
261 // ellipsis, this was removed because:
262 // 1) it was ugly with big bodies;
263 // 2) it was not indented properly;
264 // 3) it wasn’t very smart (see #675).
265 span_lint_and_then(cx,
268 "this loop could be written as a `while let` loop",
270 let sug = format!("while let {} = {} {{ .. }}",
271 snippet(cx, arms[0].pats[0].span, ".."),
272 snippet(cx, matchexpr.span, ".."));
273 db.span_suggestion(expr.span, "try", sug);
282 if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
283 let pat = &arms[0].pats[0].node;
284 if let (&PatKind::TupleStruct(ref path, ref pat_args, _),
285 &ExprMethodCall(method_name, _, ref method_args)) = (pat, &match_expr.node) {
286 let iter_expr = &method_args[0];
287 if let Some(lhs_constructor) = path.segments.last() {
288 if method_name.node.as_str() == "next" &&
289 match_trait_method(cx, match_expr, &paths::ITERATOR) &&
290 lhs_constructor.name.as_str() == "Some" &&
291 !is_iterator_used_after_while_let(cx, iter_expr) {
292 let iterator = snippet(cx, method_args[0].span, "_");
293 let loop_var = snippet(cx, pat_args[0].span, "_");
294 span_lint_and_then(cx,
295 WHILE_LET_ON_ITERATOR,
297 "this loop could be written as a `for` loop",
299 db.span_suggestion(expr.span,
301 format!("for {} in {} {{ .. }}", loop_var, iterator));
309 fn check_stmt(&mut self, cx: &LateContext, stmt: &Stmt) {
310 if let StmtSemi(ref expr, _) = stmt.node {
311 if let ExprMethodCall(ref method, _, ref args) = expr.node {
312 if args.len() == 1 && method.node.as_str() == "collect" &&
313 match_trait_method(cx, expr, &paths::ITERATOR) {
317 "you are collect()ing an iterator and throwing away the result. \
318 Consider using an explicit for loop to exhaust the iterator");
325 fn check_for_loop(cx: &LateContext, pat: &Pat, arg: &Expr, body: &Expr, expr: &Expr) {
326 check_for_loop_range(cx, pat, arg, body, expr);
327 check_for_loop_reverse_range(cx, arg, expr);
328 check_for_loop_arg(cx, pat, arg, expr);
329 check_for_loop_explicit_counter(cx, arg, body, expr);
330 check_for_loop_over_map_kv(cx, pat, arg, body, expr);
333 /// Check for looping over a range and then indexing a sequence with it.
334 /// The iteratee must be a range literal.
335 fn check_for_loop_range(cx: &LateContext, pat: &Pat, arg: &Expr, body: &Expr, expr: &Expr) {
336 if let Some(UnsugaredRange { start: Some(ref start), ref end, .. }) = unsugar_range(arg) {
337 // the var must be a single name
338 if let PatKind::Binding(_, ref ident, _) = pat.node {
339 let mut visitor = VarVisitor {
342 indexed: HashMap::new(),
345 walk_expr(&mut visitor, body);
347 // linting condition: we only indexed one variable
348 if visitor.indexed.len() == 1 {
349 let (indexed, indexed_extent) = visitor.indexed
352 .unwrap_or_else(|| unreachable!() /* len == 1 */);
354 // ensure that the indexed variable was declared before the loop, see #601
355 if let Some(indexed_extent) = indexed_extent {
356 let pat_extent = cx.tcx.region_maps.var_scope(pat.id);
357 if cx.tcx.region_maps.is_subscope_of(indexed_extent, pat_extent) {
362 let starts_at_zero = is_integer_literal(start, 0);
364 let skip: Cow<_> = if starts_at_zero {
367 format!(".skip({})", snippet(cx, start.span, "..")).into()
370 let take: Cow<_> = if let Some(ref end) = *end {
371 if is_len_call(end, &indexed) {
374 format!(".take({})", snippet(cx, end.span, "..")).into()
380 if visitor.nonindex {
384 &format!("the loop variable `{}` is used to index `{}`. Consider using `for ({}, \
385 item) in {}.iter().enumerate(){}{}` or similar iterators",
393 let repl = if starts_at_zero && take.is_empty() {
394 format!("&{}", indexed)
396 format!("{}.iter(){}{}", indexed, take, skip)
402 &format!("the loop variable `{}` is only used to index `{}`. \
403 Consider using `for item in {}` or similar iterators",
413 fn is_len_call(expr: &Expr, var: &Name) -> bool {
415 let ExprMethodCall(method, _, ref len_args) = expr.node,
417 method.node.as_str() == "len",
418 let ExprPath(_, ref path) = len_args[0].node,
419 path.segments.len() == 1,
420 &path.segments[0].name == var
428 fn check_for_loop_reverse_range(cx: &LateContext, arg: &Expr, expr: &Expr) {
429 // if this for loop is iterating over a two-sided range...
430 if let Some(UnsugaredRange { start: Some(ref start), end: Some(ref end), limits }) = unsugar_range(arg) {
431 // ...and both sides are compile-time constant integers...
432 if let Ok(start_idx) = eval_const_expr_partial(cx.tcx, start, ExprTypeChecked, None) {
433 if let Ok(end_idx) = eval_const_expr_partial(cx.tcx, end, ExprTypeChecked, None) {
434 // ...and the start index is greater than the end index,
435 // this loop will never run. This is often confusing for developers
436 // who think that this will iterate from the larger value to the
438 let (sup, eq) = match (start_idx, end_idx) {
439 (ConstVal::Integral(start_idx), ConstVal::Integral(end_idx)) => {
440 (start_idx > end_idx, start_idx == end_idx)
446 let start_snippet = snippet(cx, start.span, "_");
447 let end_snippet = snippet(cx, end.span, "_");
448 let dots = if limits == ast::RangeLimits::Closed {
454 span_lint_and_then(cx,
457 "this range is empty so this for loop will never run",
459 db.span_suggestion(arg.span,
460 "consider using the following if \
461 you are attempting to iterate \
462 over this range in reverse",
463 format!("({end}{dots}{start}).rev()",
466 start=start_snippet));
468 } else if eq && limits != ast::RangeLimits::Closed {
469 // if they are equal, it's also problematic - this loop
474 "this range is empty so this for loop will never run");
481 fn check_for_loop_arg(cx: &LateContext, pat: &Pat, arg: &Expr, expr: &Expr) {
482 let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
483 if let ExprMethodCall(ref method, _, ref args) = arg.node {
484 // just the receiver, no arguments
486 let method_name = method.node;
487 // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
488 if method_name.as_str() == "iter" || method_name.as_str() == "iter_mut" {
489 if is_ref_iterable_type(cx, &args[0]) {
490 let object = snippet(cx, args[0].span, "_");
494 &format!("it is more idiomatic to loop over `&{}{}` instead of `{}.{}()`",
495 if method_name.as_str() == "iter_mut" {
504 } else if method_name.as_str() == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
508 "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
509 probably not what you want");
510 next_loop_linted = true;
514 if !next_loop_linted {
515 check_arg_type(cx, pat, arg);
519 /// Check for `for` loops over `Option`s and `Results`
520 fn check_arg_type(cx: &LateContext, pat: &Pat, arg: &Expr) {
521 let ty = cx.tcx.expr_ty(arg);
522 if match_type(cx, ty, &paths::OPTION) {
523 span_help_and_lint(cx,
524 FOR_LOOP_OVER_OPTION,
526 &format!("for loop over `{0}`, which is an `Option`. This is more readably written as an \
527 `if let` statement.",
528 snippet(cx, arg.span, "_")),
529 &format!("consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
530 snippet(cx, pat.span, "_"),
531 snippet(cx, arg.span, "_")));
532 } else if match_type(cx, ty, &paths::RESULT) {
533 span_help_and_lint(cx,
534 FOR_LOOP_OVER_RESULT,
536 &format!("for loop over `{0}`, which is a `Result`. This is more readably written as an \
537 `if let` statement.",
538 snippet(cx, arg.span, "_")),
539 &format!("consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
540 snippet(cx, pat.span, "_"),
541 snippet(cx, arg.span, "_")));
545 fn check_for_loop_explicit_counter(cx: &LateContext, arg: &Expr, body: &Expr, expr: &Expr) {
546 // Look for variables that are incremented once per loop iteration.
547 let mut visitor = IncrementVisitor {
549 states: HashMap::new(),
553 walk_expr(&mut visitor, body);
555 // For each candidate, check the parent block to see if
556 // it's initialized to zero at the start of the loop.
557 let map = &cx.tcx.map;
558 let parent_scope = map.get_enclosing_scope(expr.id).and_then(|id| map.get_enclosing_scope(id));
559 if let Some(parent_id) = parent_scope {
560 if let NodeBlock(block) = map.get(parent_id) {
561 for (id, _) in visitor.states.iter().filter(|&(_, v)| *v == VarState::IncrOnce) {
562 let mut visitor2 = InitializeVisitor {
566 state: VarState::IncrOnce,
571 walk_block(&mut visitor2, block);
573 if visitor2.state == VarState::Warn {
574 if let Some(name) = visitor2.name {
576 EXPLICIT_COUNTER_LOOP,
578 &format!("the variable `{0}` is used as a loop counter. Consider using `for ({0}, \
579 item) in {1}.enumerate()` or similar iterators",
581 snippet(cx, arg.span, "_")));
589 /// Check for the `FOR_KV_MAP` lint.
590 fn check_for_loop_over_map_kv(cx: &LateContext, pat: &Pat, arg: &Expr, body: &Expr, expr: &Expr) {
591 if let PatKind::Tuple(ref pat, _) = pat.node {
593 let (pat_span, kind) = match (&pat[0].node, &pat[1].node) {
594 (key, _) if pat_is_wild(key, body) => (&pat[1].span, "values"),
595 (_, value) if pat_is_wild(value, body) => (&pat[0].span, "keys"),
599 let arg_span = match arg.node {
600 ExprAddrOf(MutImmutable, ref expr) => expr.span,
601 ExprAddrOf(MutMutable, _) => return, // for _ in &mut _, there is no {values,keys}_mut method
605 let ty = walk_ptrs_ty(cx.tcx.expr_ty(arg));
606 if match_type(cx, ty, &paths::HASHMAP) || match_type(cx, ty, &paths::BTREEMAP) {
607 span_lint_and_then(cx,
610 &format!("you seem to want to iterate on a map's {}", kind),
612 db.span_suggestion(expr.span,
613 "use the corresponding method",
614 format!("for {} in {}.{}() {{ .. }}",
615 snippet(cx, *pat_span, ".."),
616 snippet(cx, arg_span, ".."),
625 /// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`.
626 fn pat_is_wild(pat: &PatKind, body: &Expr) -> bool {
628 PatKind::Wild => true,
629 PatKind::Binding(_, ident, None) if ident.node.as_str().starts_with('_') => {
630 let mut visitor = UsedVisitor {
634 walk_expr(&mut visitor, body);
642 var: ast::Name, // var to look for
643 used: bool, // has the var been used otherwise?
646 impl<'a> Visitor<'a> for UsedVisitor {
647 fn visit_expr(&mut self, expr: &Expr) {
648 if let ExprPath(None, ref path) = expr.node {
649 if path.segments.len() == 1 && path.segments[0].name == self.var {
655 walk_expr(self, expr);
659 struct VarVisitor<'v, 't: 'v> {
660 cx: &'v LateContext<'v, 't>, // context reference
661 var: Name, // var name to look for as index
662 indexed: HashMap<Name, Option<CodeExtent>>, // indexed variables, the extent is None for global
663 nonindex: bool, // has the var been used otherwise?
666 impl<'v, 't> Visitor<'v> for VarVisitor<'v, 't> {
667 fn visit_expr(&mut self, expr: &'v Expr) {
668 if let ExprPath(None, ref path) = expr.node {
669 if path.segments.len() == 1 && path.segments[0].name == self.var {
670 // we are referencing our variable! now check if it's as an index
672 let Some(parexpr) = get_parent_expr(self.cx, expr),
673 let ExprIndex(ref seqexpr, _) = parexpr.node,
674 let ExprPath(None, ref seqvar) = seqexpr.node,
675 seqvar.segments.len() == 1
677 let def_map = self.cx.tcx.def_map.borrow();
678 if let Some(def) = def_map.get(&seqexpr.id) {
680 Def::Local(..) | Def::Upvar(..) => {
681 let extent = self.cx.tcx.region_maps.var_scope(def.base_def.var_id());
682 self.indexed.insert(seqvar.segments[0].name, Some(extent));
683 return; // no need to walk further
685 Def::Static(..) | Def::Const(..) => {
686 self.indexed.insert(seqvar.segments[0].name, None);
687 return; // no need to walk further
693 // we are not indexing anything, record that
694 self.nonindex = true;
698 walk_expr(self, expr);
702 fn is_iterator_used_after_while_let(cx: &LateContext, iter_expr: &Expr) -> bool {
703 let def_id = match var_def_id(cx, iter_expr) {
705 None => return false,
707 let mut visitor = VarUsedAfterLoopVisitor {
710 iter_expr_id: iter_expr.id,
711 past_while_let: false,
712 var_used_after_while_let: false,
714 if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
715 walk_block(&mut visitor, enclosing_block);
717 visitor.var_used_after_while_let
720 struct VarUsedAfterLoopVisitor<'v, 't: 'v> {
721 cx: &'v LateContext<'v, 't>,
723 iter_expr_id: NodeId,
724 past_while_let: bool,
725 var_used_after_while_let: bool,
728 impl<'v, 't> Visitor<'v> for VarUsedAfterLoopVisitor<'v, 't> {
729 fn visit_expr(&mut self, expr: &'v Expr) {
730 if self.past_while_let {
731 if Some(self.def_id) == var_def_id(self.cx, expr) {
732 self.var_used_after_while_let = true;
734 } else if self.iter_expr_id == expr.id {
735 self.past_while_let = true;
737 walk_expr(self, expr);
742 /// Return true if the type of expr is one that provides `IntoIterator` impls
743 /// for `&T` and `&mut T`, such as `Vec`.
744 #[cfg_attr(rustfmt, rustfmt_skip)]
745 fn is_ref_iterable_type(cx: &LateContext, e: &Expr) -> bool {
746 // no walk_ptrs_ty: calling iter() on a reference can make sense because it
747 // will allow further borrows afterwards
748 let ty = cx.tcx.expr_ty(e);
749 is_iterable_array(ty) ||
750 match_type(cx, ty, &paths::VEC) ||
751 match_type(cx, ty, &paths::LINKED_LIST) ||
752 match_type(cx, ty, &paths::HASHMAP) ||
753 match_type(cx, ty, &paths::HASHSET) ||
754 match_type(cx, ty, &paths::VEC_DEQUE) ||
755 match_type(cx, ty, &paths::BINARY_HEAP) ||
756 match_type(cx, ty, &paths::BTREEMAP) ||
757 match_type(cx, ty, &paths::BTREESET)
760 fn is_iterable_array(ty: ty::Ty) -> bool {
761 // IntoIterator is currently only implemented for array sizes <= 32 in rustc
763 ty::TyArray(_, 0...32) => true,
768 /// If a block begins with a statement (possibly a `let` binding) and has an expression, return it.
769 fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
770 if block.stmts.is_empty() {
773 if let StmtDecl(ref decl, _) = block.stmts[0].node {
774 if let DeclLocal(ref local) = decl.node {
775 if let Some(ref expr) = local.init {
788 /// If a block begins with an expression (with or without semicolon), return it.
789 fn extract_first_expr(block: &Block) -> Option<&Expr> {
791 Some(ref expr) if block.stmts.is_empty() => Some(expr),
792 None if !block.stmts.is_empty() => {
793 match block.stmts[0].node {
794 StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => Some(expr),
795 StmtDecl(..) => None,
802 /// Return true if expr contains a single break expr (maybe within a block).
803 fn is_break_expr(expr: &Expr) -> bool {
805 ExprBreak(None) => true,
806 ExprBlock(ref b) => {
807 match extract_first_expr(b) {
808 Some(ref subexpr) => is_break_expr(subexpr),
816 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
817 // incremented exactly once in the loop body, and initialized to zero
818 // at the start of the loop.
821 Initial, // Not examined yet
822 IncrOnce, // Incremented exactly once, may be a loop counter
823 Declared, // Declared but not (yet) initialized to zero
828 /// Scan a for loop for variables that are incremented exactly once.
829 struct IncrementVisitor<'v, 't: 'v> {
830 cx: &'v LateContext<'v, 't>, // context reference
831 states: HashMap<NodeId, VarState>, // incremented variables
832 depth: u32, // depth of conditional expressions
836 impl<'v, 't> Visitor<'v> for IncrementVisitor<'v, 't> {
837 fn visit_expr(&mut self, expr: &'v Expr) {
842 // If node is a variable
843 if let Some(def_id) = var_def_id(self.cx, expr) {
844 if let Some(parent) = get_parent_expr(self.cx, expr) {
845 let state = self.states.entry(def_id).or_insert(VarState::Initial);
848 ExprAssignOp(op, ref lhs, ref rhs) => {
849 if lhs.id == expr.id {
850 if op.node == BiAdd && is_integer_literal(rhs, 1) {
851 *state = match *state {
852 VarState::Initial if self.depth == 0 => VarState::IncrOnce,
853 _ => VarState::DontWarn,
856 // Assigned some other value
857 *state = VarState::DontWarn;
861 ExprAssign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
862 ExprAddrOf(mutability, _) if mutability == MutMutable => *state = VarState::DontWarn,
866 } else if is_loop(expr) {
870 } else if is_conditional(expr) {
872 walk_expr(self, expr);
876 walk_expr(self, expr);
880 /// Check whether a variable is initialized to zero at the start of a loop.
881 struct InitializeVisitor<'v, 't: 'v> {
882 cx: &'v LateContext<'v, 't>, // context reference
883 end_expr: &'v Expr, // the for loop. Stop scanning here.
887 depth: u32, // depth of conditional expressions
891 impl<'v, 't> Visitor<'v> for InitializeVisitor<'v, 't> {
892 fn visit_decl(&mut self, decl: &'v Decl) {
893 // Look for declarations of the variable
894 if let DeclLocal(ref local) = decl.node {
895 if local.pat.id == self.var_id {
896 if let PatKind::Binding(_, ref ident, _) = local.pat.node {
897 self.name = Some(ident.node);
899 self.state = if let Some(ref init) = local.init {
900 if is_integer_literal(init, 0) {
911 walk_decl(self, decl);
914 fn visit_expr(&mut self, expr: &'v Expr) {
915 if self.state == VarState::DontWarn {
918 if expr == self.end_expr {
919 self.past_loop = true;
922 // No need to visit expressions before the variable is
924 if self.state == VarState::IncrOnce {
928 // If node is the desired variable, see how it's used
929 if var_def_id(self.cx, expr) == Some(self.var_id) {
930 if let Some(parent) = get_parent_expr(self.cx, expr) {
932 ExprAssignOp(_, ref lhs, _) if lhs.id == expr.id => {
933 self.state = VarState::DontWarn;
935 ExprAssign(ref lhs, ref rhs) if lhs.id == expr.id => {
936 self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
942 ExprAddrOf(mutability, _) if mutability == MutMutable => self.state = VarState::DontWarn,
948 self.state = VarState::DontWarn;
951 } else if !self.past_loop && is_loop(expr) {
952 self.state = VarState::DontWarn;
954 } else if is_conditional(expr) {
956 walk_expr(self, expr);
960 walk_expr(self, expr);
964 fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
965 if let Some(path_res) = cx.tcx.def_map.borrow().get(&expr.id) {
966 if let Def::Local(_, node_id) = path_res.base_def {
967 return Some(node_id);
973 fn is_loop(expr: &Expr) -> bool {
975 ExprLoop(..) | ExprWhile(..) => true,
980 fn is_conditional(expr: &Expr) -> bool {
982 ExprIf(..) | ExprMatch(..) => true,