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 && arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
253 arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
254 is_break_expr(&arms[1].body) {
255 if in_external_macro(cx, expr.span) {
259 // NOTE: we used to make build a body here instead of using
260 // ellipsis, this was removed because:
261 // 1) it was ugly with big bodies;
262 // 2) it was not indented properly;
263 // 3) it wasn’t very smart (see #675).
264 span_lint_and_then(cx,
267 "this loop could be written as a `while let` loop",
269 let sug = format!("while let {} = {} {{ .. }}",
270 snippet(cx, arms[0].pats[0].span, ".."),
271 snippet(cx, matchexpr.span, ".."));
272 db.span_suggestion(expr.span, "try", sug);
281 if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
282 let pat = &arms[0].pats[0].node;
283 if let (&PatKind::TupleStruct(ref path, Some(ref pat_args)),
284 &ExprMethodCall(method_name, _, ref method_args)) = (pat, &match_expr.node) {
285 let iter_expr = &method_args[0];
286 if let Some(lhs_constructor) = path.segments.last() {
287 if method_name.node.as_str() == "next" &&
288 match_trait_method(cx, match_expr, &paths::ITERATOR) &&
289 lhs_constructor.identifier.name.as_str() == "Some" &&
290 !is_iterator_used_after_while_let(cx, iter_expr) {
291 let iterator = snippet(cx, method_args[0].span, "_");
292 let loop_var = snippet(cx, pat_args[0].span, "_");
293 span_help_and_lint(cx,
294 WHILE_LET_ON_ITERATOR,
296 "this loop could be written as a `for` loop",
297 &format!("try\nfor {} in {} {{...}}", loop_var, iterator));
304 fn check_stmt(&mut self, cx: &LateContext, stmt: &Stmt) {
305 if let StmtSemi(ref expr, _) = stmt.node {
306 if let ExprMethodCall(ref method, _, ref args) = expr.node {
307 if args.len() == 1 && method.node.as_str() == "collect" &&
308 match_trait_method(cx, expr, &paths::ITERATOR) {
312 "you are collect()ing an iterator and throwing away the result. \
313 Consider using an explicit for loop to exhaust the iterator");
320 fn check_for_loop(cx: &LateContext, pat: &Pat, arg: &Expr, body: &Expr, expr: &Expr) {
321 check_for_loop_range(cx, pat, arg, body, expr);
322 check_for_loop_reverse_range(cx, arg, expr);
323 check_for_loop_arg(cx, pat, arg, expr);
324 check_for_loop_explicit_counter(cx, arg, body, expr);
325 check_for_loop_over_map_kv(cx, pat, arg, body, expr);
328 /// Check for looping over a range and then indexing a sequence with it.
329 /// The iteratee must be a range literal.
330 fn check_for_loop_range(cx: &LateContext, pat: &Pat, arg: &Expr, body: &Expr, expr: &Expr) {
331 if let Some(UnsugaredRange { start: Some(ref start), ref end, .. }) = unsugar_range(&arg) {
332 // the var must be a single name
333 if let PatKind::Ident(_, ref ident, _) = pat.node {
334 let mut visitor = VarVisitor {
336 var: ident.node.name,
337 indexed: HashMap::new(),
340 walk_expr(&mut visitor, body);
342 // linting condition: we only indexed one variable
343 if visitor.indexed.len() == 1 {
344 let (indexed, indexed_extent) = visitor.indexed
347 .unwrap_or_else(|| unreachable!() /* len == 1 */);
349 // ensure that the indexed variable was declared before the loop, see #601
350 if let Some(indexed_extent) = indexed_extent {
351 let pat_extent = cx.tcx.region_maps.var_scope(pat.id);
352 if cx.tcx.region_maps.is_subscope_of(indexed_extent, pat_extent) {
357 let starts_at_zero = is_integer_literal(start, 0);
359 let skip: Cow<_> = if starts_at_zero {
362 format!(".skip({})", snippet(cx, start.span, "..")).into()
365 let take: Cow<_> = if let Some(ref end) = *end {
366 if is_len_call(&end, &indexed) {
369 format!(".take({})", snippet(cx, end.span, "..")).into()
375 if visitor.nonindex {
379 &format!("the loop variable `{}` is used to index `{}`. Consider using `for ({}, \
380 item) in {}.iter().enumerate(){}{}` or similar iterators",
388 let repl = if starts_at_zero && take.is_empty() {
389 format!("&{}", indexed)
391 format!("{}.iter(){}{}", indexed, take, skip)
397 &format!("the loop variable `{}` is only used to index `{}`. \
398 Consider using `for item in {}` or similar iterators",
408 fn is_len_call(expr: &Expr, var: &Name) -> bool {
410 let ExprMethodCall(method, _, ref len_args) = expr.node,
412 method.node.as_str() == "len",
413 let ExprPath(_, ref path) = len_args[0].node,
414 path.segments.len() == 1,
415 &path.segments[0].identifier.name == var
423 fn check_for_loop_reverse_range(cx: &LateContext, arg: &Expr, expr: &Expr) {
424 // if this for loop is iterating over a two-sided range...
425 if let Some(UnsugaredRange { start: Some(ref start), end: Some(ref end), limits }) = unsugar_range(&arg) {
426 // ...and both sides are compile-time constant integers...
427 if let Ok(start_idx) = eval_const_expr_partial(&cx.tcx, start, ExprTypeChecked, None) {
428 if let Ok(end_idx) = eval_const_expr_partial(&cx.tcx, end, ExprTypeChecked, None) {
429 // ...and the start index is greater than the end index,
430 // this loop will never run. This is often confusing for developers
431 // who think that this will iterate from the larger value to the
433 let (sup, eq) = match (start_idx, end_idx) {
434 (ConstVal::Integral(start_idx), ConstVal::Integral(end_idx)) => {
435 (start_idx > end_idx, start_idx == end_idx)
441 let start_snippet = snippet(cx, start.span, "_");
442 let end_snippet = snippet(cx, end.span, "_");
444 span_lint_and_then(cx,
447 "this range is empty so this for loop will never run",
449 db.span_suggestion(expr.span,
450 "consider using the following if \
451 you are attempting to iterate \
452 over this range in reverse",
453 format!("({}..{}).rev()` ", end_snippet, start_snippet));
455 } else if eq && limits != ast::RangeLimits::Closed {
456 // if they are equal, it's also problematic - this loop
461 "this range is empty so this for loop will never run");
468 fn check_for_loop_arg(cx: &LateContext, pat: &Pat, arg: &Expr, expr: &Expr) {
469 let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
470 if let ExprMethodCall(ref method, _, ref args) = arg.node {
471 // just the receiver, no arguments
473 let method_name = method.node;
474 // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
475 if method_name.as_str() == "iter" || method_name.as_str() == "iter_mut" {
476 if is_ref_iterable_type(cx, &args[0]) {
477 let object = snippet(cx, args[0].span, "_");
481 &format!("it is more idiomatic to loop over `&{}{}` instead of `{}.{}()`",
482 if method_name.as_str() == "iter_mut" {
491 } else if method_name.as_str() == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
495 "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
496 probably not what you want");
497 next_loop_linted = true;
501 if !next_loop_linted {
502 check_arg_type(cx, pat, arg);
506 /// Check for `for` loops over `Option`s and `Results`
507 fn check_arg_type(cx: &LateContext, pat: &Pat, arg: &Expr) {
508 let ty = cx.tcx.expr_ty(arg);
509 if match_type(cx, ty, &paths::OPTION) {
510 span_help_and_lint(cx,
511 FOR_LOOP_OVER_OPTION,
513 &format!("for loop over `{0}`, which is an `Option`. This is more readably written as an \
514 `if let` statement.",
515 snippet(cx, arg.span, "_")),
516 &format!("consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
517 snippet(cx, pat.span, "_"),
518 snippet(cx, arg.span, "_")));
519 } else if match_type(cx, ty, &paths::RESULT) {
520 span_help_and_lint(cx,
521 FOR_LOOP_OVER_RESULT,
523 &format!("for loop over `{0}`, which is a `Result`. This is more readably written as an \
524 `if let` statement.",
525 snippet(cx, arg.span, "_")),
526 &format!("consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
527 snippet(cx, pat.span, "_"),
528 snippet(cx, arg.span, "_")));
532 fn check_for_loop_explicit_counter(cx: &LateContext, arg: &Expr, body: &Expr, expr: &Expr) {
533 // Look for variables that are incremented once per loop iteration.
534 let mut visitor = IncrementVisitor {
536 states: HashMap::new(),
540 walk_expr(&mut visitor, body);
542 // For each candidate, check the parent block to see if
543 // it's initialized to zero at the start of the loop.
544 let map = &cx.tcx.map;
545 let parent_scope = map.get_enclosing_scope(expr.id).and_then(|id| map.get_enclosing_scope(id));
546 if let Some(parent_id) = parent_scope {
547 if let NodeBlock(block) = map.get(parent_id) {
548 for (id, _) in visitor.states.iter().filter(|&(_, v)| *v == VarState::IncrOnce) {
549 let mut visitor2 = InitializeVisitor {
553 state: VarState::IncrOnce,
558 walk_block(&mut visitor2, block);
560 if visitor2.state == VarState::Warn {
561 if let Some(name) = visitor2.name {
563 EXPLICIT_COUNTER_LOOP,
565 &format!("the variable `{0}` is used as a loop counter. Consider using `for ({0}, \
566 item) in {1}.enumerate()` or similar iterators",
568 snippet(cx, arg.span, "_")));
576 /// Check for the `FOR_KV_MAP` lint.
577 fn check_for_loop_over_map_kv(cx: &LateContext, pat: &Pat, arg: &Expr, body: &Expr, expr: &Expr) {
578 if let PatKind::Tup(ref pat) = pat.node {
580 let (pat_span, kind) = match (&pat[0].node, &pat[1].node) {
581 (key, _) if pat_is_wild(key, body) => (&pat[1].span, "values"),
582 (_, value) if pat_is_wild(value, body) => (&pat[0].span, "keys"),
586 let arg_span = match arg.node {
587 ExprAddrOf(MutImmutable, ref expr) => expr.span,
588 ExprAddrOf(MutMutable, _) => return, // for _ in &mut _, there is no {values,keys}_mut method
592 let ty = walk_ptrs_ty(cx.tcx.expr_ty(arg));
593 if match_type(cx, ty, &paths::HASHMAP) || match_type(cx, ty, &paths::BTREEMAP) {
594 span_lint_and_then(cx,
597 &format!("you seem to want to iterate on a map's {}", kind),
599 db.span_suggestion(expr.span,
600 "use the corresponding method",
601 format!("for {} in {}.{}() {{...}}",
602 snippet(cx, *pat_span, ".."),
603 snippet(cx, arg_span, ".."),
612 /// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`.
613 fn pat_is_wild(pat: &PatKind, body: &Expr) -> bool {
615 PatKind::Wild => true,
616 PatKind::Ident(_, ident, None) if ident.node.name.as_str().starts_with('_') => {
617 let mut visitor = UsedVisitor {
621 walk_expr(&mut visitor, body);
629 var: Ident, // var to look for
630 used: bool, // has the var been used otherwise?
633 impl<'a> Visitor<'a> for UsedVisitor {
634 fn visit_expr(&mut self, expr: &Expr) {
635 if let ExprPath(None, ref path) = expr.node {
636 if path.segments.len() == 1 && path.segments[0].identifier == self.var {
642 walk_expr(self, expr);
646 struct VarVisitor<'v, 't: 'v> {
647 cx: &'v LateContext<'v, 't>, // context reference
648 var: Name, // var name to look for as index
649 indexed: HashMap<Name, Option<CodeExtent>>, // indexed variables, the extent is None for global
650 nonindex: bool, // has the var been used otherwise?
653 impl<'v, 't> Visitor<'v> for VarVisitor<'v, 't> {
654 fn visit_expr(&mut self, expr: &'v Expr) {
655 if let ExprPath(None, ref path) = expr.node {
656 if path.segments.len() == 1 && path.segments[0].identifier.name == self.var {
657 // we are referencing our variable! now check if it's as an index
660 let Some(parexpr) = get_parent_expr(self.cx, expr),
661 let ExprIndex(ref seqexpr, _) = parexpr.node,
662 let ExprPath(None, ref seqvar) = seqexpr.node,
663 seqvar.segments.len() == 1
665 let def_map = self.cx.tcx.def_map.borrow();
666 if let Some(def) = def_map.get(&seqexpr.id) {
668 Def::Local(..) | Def::Upvar(..) => {
669 let extent = self.cx.tcx.region_maps.var_scope(def.base_def.var_id());
670 self.indexed.insert(seqvar.segments[0].identifier.name, Some(extent));
671 return; // no need to walk further
673 Def::Static(..) | Def::Const(..) => {
674 self.indexed.insert(seqvar.segments[0].identifier.name, None);
675 return; // no need to walk further
682 // we are not indexing anything, record that
683 self.nonindex = true;
687 walk_expr(self, expr);
691 fn is_iterator_used_after_while_let(cx: &LateContext, iter_expr: &Expr) -> bool {
692 let def_id = match var_def_id(cx, iter_expr) {
694 None => return false,
696 let mut visitor = VarUsedAfterLoopVisitor {
699 iter_expr_id: iter_expr.id,
700 past_while_let: false,
701 var_used_after_while_let: false,
703 if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
704 walk_block(&mut visitor, enclosing_block);
706 visitor.var_used_after_while_let
709 struct VarUsedAfterLoopVisitor<'v, 't: 'v> {
710 cx: &'v LateContext<'v, 't>,
712 iter_expr_id: NodeId,
713 past_while_let: bool,
714 var_used_after_while_let: bool,
717 impl<'v, 't> Visitor<'v> for VarUsedAfterLoopVisitor<'v, 't> {
718 fn visit_expr(&mut self, expr: &'v Expr) {
719 if self.past_while_let {
720 if Some(self.def_id) == var_def_id(self.cx, expr) {
721 self.var_used_after_while_let = true;
723 } else if self.iter_expr_id == expr.id {
724 self.past_while_let = true;
726 walk_expr(self, expr);
731 /// Return true if the type of expr is one that provides `IntoIterator` impls
732 /// for `&T` and `&mut T`, such as `Vec`.
733 #[cfg_attr(rustfmt, rustfmt_skip)]
734 fn is_ref_iterable_type(cx: &LateContext, e: &Expr) -> bool {
735 // no walk_ptrs_ty: calling iter() on a reference can make sense because it
736 // will allow further borrows afterwards
737 let ty = cx.tcx.expr_ty(e);
738 is_iterable_array(ty) ||
739 match_type(cx, ty, &paths::VEC) ||
740 match_type(cx, ty, &paths::LINKED_LIST) ||
741 match_type(cx, ty, &paths::HASHMAP) ||
742 match_type(cx, ty, &paths::HASHSET) ||
743 match_type(cx, ty, &paths::VEC_DEQUE) ||
744 match_type(cx, ty, &paths::BINARY_HEAP) ||
745 match_type(cx, ty, &paths::BTREEMAP) ||
746 match_type(cx, ty, &paths::BTREESET)
749 fn is_iterable_array(ty: ty::Ty) -> bool {
750 // IntoIterator is currently only implemented for array sizes <= 32 in rustc
752 ty::TyArray(_, 0...32) => true,
757 /// If a block begins with a statement (possibly a `let` binding) and has an expression, return it.
758 fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
759 if block.stmts.is_empty() {
762 if let StmtDecl(ref decl, _) = block.stmts[0].node {
763 if let DeclLocal(ref local) = decl.node {
764 if let Some(ref expr) = local.init {
777 /// If a block begins with an expression (with or without semicolon), return it.
778 fn extract_first_expr(block: &Block) -> Option<&Expr> {
780 Some(ref expr) => Some(expr),
781 None if !block.stmts.is_empty() => {
782 match block.stmts[0].node {
783 StmtExpr(ref expr, _) |
784 StmtSemi(ref expr, _) => Some(expr),
792 /// Return true if expr contains a single break expr (maybe within a block).
793 fn is_break_expr(expr: &Expr) -> bool {
795 ExprBreak(None) => true,
796 // there won't be a `let <pat> = break` and so we can safely ignore the StmtDecl case
797 ExprBlock(ref b) => {
798 match extract_first_expr(b) {
799 Some(ref subexpr) => is_break_expr(subexpr),
807 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
808 // incremented exactly once in the loop body, and initialized to zero
809 // at the start of the loop.
812 Initial, // Not examined yet
813 IncrOnce, // Incremented exactly once, may be a loop counter
814 Declared, // Declared but not (yet) initialized to zero
819 /// Scan a for loop for variables that are incremented exactly once.
820 struct IncrementVisitor<'v, 't: 'v> {
821 cx: &'v LateContext<'v, 't>, // context reference
822 states: HashMap<NodeId, VarState>, // incremented variables
823 depth: u32, // depth of conditional expressions
827 impl<'v, 't> Visitor<'v> for IncrementVisitor<'v, 't> {
828 fn visit_expr(&mut self, expr: &'v Expr) {
833 // If node is a variable
834 if let Some(def_id) = var_def_id(self.cx, expr) {
835 if let Some(parent) = get_parent_expr(self.cx, expr) {
836 let state = self.states.entry(def_id).or_insert(VarState::Initial);
839 ExprAssignOp(op, ref lhs, ref rhs) => {
840 if lhs.id == expr.id {
841 if op.node == BiAdd && is_integer_literal(rhs, 1) {
842 *state = match *state {
843 VarState::Initial if self.depth == 0 => VarState::IncrOnce,
844 _ => VarState::DontWarn,
847 // Assigned some other value
848 *state = VarState::DontWarn;
852 ExprAssign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
853 ExprAddrOf(mutability, _) if mutability == MutMutable => *state = VarState::DontWarn,
857 } else if is_loop(expr) {
861 } else if is_conditional(expr) {
863 walk_expr(self, expr);
867 walk_expr(self, expr);
871 /// Check whether a variable is initialized to zero at the start of a loop.
872 struct InitializeVisitor<'v, 't: 'v> {
873 cx: &'v LateContext<'v, 't>, // context reference
874 end_expr: &'v Expr, // the for loop. Stop scanning here.
878 depth: u32, // depth of conditional expressions
882 impl<'v, 't> Visitor<'v> for InitializeVisitor<'v, 't> {
883 fn visit_decl(&mut self, decl: &'v Decl) {
884 // Look for declarations of the variable
885 if let DeclLocal(ref local) = decl.node {
886 if local.pat.id == self.var_id {
887 if let PatKind::Ident(_, ref ident, _) = local.pat.node {
888 self.name = Some(ident.node.name);
890 self.state = if let Some(ref init) = local.init {
891 if is_integer_literal(init, 0) {
902 walk_decl(self, decl);
905 fn visit_expr(&mut self, expr: &'v Expr) {
906 if self.state == VarState::DontWarn {
909 if expr == self.end_expr {
910 self.past_loop = true;
913 // No need to visit expressions before the variable is
915 if self.state == VarState::IncrOnce {
919 // If node is the desired variable, see how it's used
920 if var_def_id(self.cx, expr) == Some(self.var_id) {
921 if let Some(parent) = get_parent_expr(self.cx, expr) {
923 ExprAssignOp(_, ref lhs, _) if lhs.id == expr.id => {
924 self.state = VarState::DontWarn;
926 ExprAssign(ref lhs, ref rhs) if lhs.id == expr.id => {
927 self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
933 ExprAddrOf(mutability, _) if mutability == MutMutable => self.state = VarState::DontWarn,
939 self.state = VarState::DontWarn;
942 } else if !self.past_loop && is_loop(expr) {
943 self.state = VarState::DontWarn;
945 } else if is_conditional(expr) {
947 walk_expr(self, expr);
951 walk_expr(self, expr);
955 fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
956 if let Some(path_res) = cx.tcx.def_map.borrow().get(&expr.id) {
957 if let Def::Local(_, node_id) = path_res.base_def {
958 return Some(node_id);
964 fn is_loop(expr: &Expr) -> bool {
966 ExprLoop(..) | ExprWhile(..) => true,
971 fn is_conditional(expr: &Expr) -> bool {
973 ExprIf(..) | ExprMatch(..) => true,