3 use rustc::hir::def::Def;
4 use rustc::hir::def_id::DefId;
5 use rustc::hir::intravisit::{Visitor, walk_expr, walk_block, walk_decl, NestedVisitorMap};
6 use rustc::hir::map::Node::NodeBlock;
8 use rustc::middle::const_val::ConstVal;
9 use rustc::middle::region::CodeExtent;
10 use rustc::ty::{self, Ty};
11 use rustc::ty::subst::Subst;
12 use rustc_const_eval::ConstContext;
13 use std::collections::HashMap;
17 use utils::{snippet, span_lint, get_parent_expr, match_trait_method, match_type, multispan_sugg, in_external_macro,
18 is_refutable, span_help_and_lint, is_integer_literal, get_enclosing_block, span_lint_and_then, higher,
19 last_path_segment, span_lint_and_sugg};
22 /// **What it does:** Checks for looping over the range of `0..len` of some
23 /// collection just to get the values by index.
25 /// **Why is this bad?** Just iterating the collection itself makes the intent
26 /// more clear and is probably faster.
28 /// **Known problems:** None.
32 /// for i in 0..vec.len() {
33 /// println!("{}", vec[i]);
37 pub NEEDLESS_RANGE_LOOP,
39 "for-looping over a range of indices where an iterator over items would do"
42 /// **What it does:** Checks for loops on `x.iter()` where `&x` will do, and
43 /// suggests the latter.
45 /// **Why is this bad?** Readability.
47 /// **Known problems:** False negatives. We currently only warn on some known
52 /// // with `y` a `Vec` or slice:
53 /// for x in y.iter() { .. }
56 pub EXPLICIT_ITER_LOOP,
58 "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
61 /// **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and
62 /// suggests the latter.
64 /// **Why is this bad?** Readability.
66 /// **Known problems:** None
70 /// // with `y` a `Vec` or slice:
71 /// for x in y.into_iter() { .. }
74 pub EXPLICIT_INTO_ITER_LOOP,
76 "for-looping over `_.into_iter()` when `_` would do"
79 /// **What it does:** Checks for loops on `x.next()`.
81 /// **Why is this bad?** `next()` returns either `Some(value)` if there was a
82 /// value, or `None` otherwise. The insidious thing is that `Option<_>`
83 /// implements `IntoIterator`, so that possibly one value will be iterated,
84 /// leading to some hard to find bugs. No one will want to write such code
85 /// [except to win an Underhanded Rust
86 /// Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
88 /// **Known problems:** None.
92 /// for x in y.next() { .. }
97 "for-looping over `_.next()` which is probably not intended"
100 /// **What it does:** Checks for `for` loops over `Option` values.
102 /// **Why is this bad?** Readability. This is more clearly expressed as an `if let`.
104 /// **Known problems:** None.
108 /// for x in option { .. }
113 /// if let Some(x) = option { .. }
116 pub FOR_LOOP_OVER_OPTION,
118 "for-looping over an `Option`, which is more clearly expressed as an `if let`"
121 /// **What it does:** Checks for `for` loops over `Result` values.
123 /// **Why is this bad?** Readability. This is more clearly expressed as an `if let`.
125 /// **Known problems:** None.
129 /// for x in result { .. }
134 /// if let Ok(x) = result { .. }
137 pub FOR_LOOP_OVER_RESULT,
139 "for-looping over a `Result`, which is more clearly expressed as an `if let`"
142 /// **What it does:** Detects `loop + match` combinations that are easier
143 /// written as a `while let` loop.
145 /// **Why is this bad?** The `while let` loop is usually shorter and more readable.
147 /// **Known problems:** Sometimes the wrong binding is displayed (#383).
152 /// let x = match y {
156 /// // .. do something with x
158 /// // is easier written as
159 /// while let Some(x) = y {
160 /// // .. do something with x
166 "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
169 /// **What it does:** Checks for using `collect()` on an iterator without using
172 /// **Why is this bad?** It is more idiomatic to use a `for` loop over the
173 /// iterator instead.
175 /// **Known problems:** None.
179 /// vec.iter().map(|x| /* some operation returning () */).collect::<Vec<_>>();
184 "`collect()`ing an iterator without using the result; this is usually better \
185 written as a for loop"
188 /// **What it does:** Checks for loops over ranges `x..y` where both `x` and `y`
189 /// are constant and `x` is greater or equal to `y`, unless the range is
190 /// reversed or has a negative `.step_by(_)`.
192 /// **Why is it bad?** Such loops will either be skipped or loop until
193 /// wrap-around (in debug code, this may `panic!()`). Both options are probably
196 /// **Known problems:** The lint cannot catch loops over dynamically defined
197 /// ranges. Doing this would require simulating all possible inputs and code
198 /// paths through the program, which would be complex and error-prone.
202 /// for x in 5..10-5 { .. } // oops, stray `-`
205 pub REVERSE_RANGE_LOOP,
207 "iteration over an empty range, such as `10..0` or `5..5`"
210 /// **What it does:** Checks `for` loops over slices with an explicit counter
211 /// and suggests the use of `.enumerate()`.
213 /// **Why is it bad?** Not only is the version using `.enumerate()` more
214 /// readable, the compiler is able to remove bounds checks which can lead to
215 /// faster code in some instances.
217 /// **Known problems:** None.
221 /// for i in 0..v.len() { foo(v[i]);
222 /// for i in 0..v.len() { bar(i, v[i]); }
225 pub EXPLICIT_COUNTER_LOOP,
227 "for-looping with an explicit counter when `_.enumerate()` would do"
230 /// **What it does:** Checks for empty `loop` expressions.
232 /// **Why is this bad?** Those busy loops burn CPU cycles without doing
233 /// anything. Think of the environment and either block on something or at least
234 /// make the thread sleep for some microseconds.
236 /// **Known problems:** None.
245 "empty `loop {}`, which should block or sleep"
248 /// **What it does:** Checks for `while let` expressions on iterators.
250 /// **Why is this bad?** Readability. A simple `for` loop is shorter and conveys
251 /// the intent better.
253 /// **Known problems:** None.
257 /// while let Some(val) = iter() { .. }
260 pub WHILE_LET_ON_ITERATOR,
262 "using a while-let loop instead of a for loop on an iterator"
265 /// **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and
266 /// ignoring either the keys or values.
268 /// **Why is this bad?** Readability. There are `keys` and `values` methods that
269 /// can be used to express that don't need the values or keys.
271 /// **Known problems:** None.
275 /// for (k, _) in &map { .. }
278 /// could be replaced by
281 /// for k in map.keys() { .. }
286 "looping on a map using `iter` when `keys` or `values` would do"
289 /// **What it does:** Checks for loops that will always `break`, `return` or
290 /// `continue` an outer loop.
292 /// **Why is this bad?** This loop never loops, all it does is obfuscating the
295 /// **Known problems:** None
299 /// loop { ..; break; }
304 "any loop that will always `break` or `return`"
307 #[derive(Copy, Clone, Default)]
312 impl LintPass for Pass {
313 fn get_lints(&self) -> LintArray {
314 lint_array!(NEEDLESS_RANGE_LOOP,
316 EXPLICIT_INTO_ITER_LOOP,
318 FOR_LOOP_OVER_RESULT,
319 FOR_LOOP_OVER_OPTION,
323 EXPLICIT_COUNTER_LOOP,
325 WHILE_LET_ON_ITERATOR,
331 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
332 fn check_expr_post(&mut self, _: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
334 ExprWhile(..) | ExprLoop(..) => { self.loop_count -= 1; }
339 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
340 if let Some((pat, arg, body)) = higher::for_loop(expr) {
341 check_for_loop(cx, pat, arg, body, expr);
344 // check for never_loop
346 ExprWhile(_, ref block, _) |
347 ExprLoop(ref block, _, _) => {
348 self.loop_count += 1;
349 if never_loop(block, &expr.id) {
350 span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops");
356 // check for `loop { if let {} else break }` that could be `while let`
357 // (also matches an explicit "match" instead of "if let")
358 // (even if the "match" or "if let" is used for declaration)
359 if let ExprLoop(ref block, _, LoopSource::Loop) = expr.node {
360 // also check for empty `loop {}` statements
361 if block.stmts.is_empty() && block.expr.is_none() {
365 "empty `loop {}` detected. You may want to either use `panic!()` or add \
366 `std::thread::sleep(..);` to the loop body.");
369 // extract the expression from the first statement (if any) in a block
370 let inner_stmt_expr = extract_expr_from_first_stmt(block);
371 // or extract the first expression (if any) from the block
372 if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
373 if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node {
374 // ensure "if let" compatible match structure
376 MatchSource::Normal |
377 MatchSource::IfLetDesugar { .. } => {
378 if arms.len() == 2 && arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
379 arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
380 is_break_expr(&arms[1].body) {
381 if in_external_macro(cx, expr.span) {
385 // NOTE: we used to make build a body here instead of using
386 // ellipsis, this was removed because:
387 // 1) it was ugly with big bodies;
388 // 2) it was not indented properly;
389 // 3) it wasn’t very smart (see #675).
390 span_lint_and_sugg(cx,
393 "this loop could be written as a `while let` loop",
395 format!("while let {} = {} {{ .. }}",
396 snippet(cx, arms[0].pats[0].span, ".."),
397 snippet(cx, matchexpr.span, "..")));
405 if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
406 let pat = &arms[0].pats[0].node;
407 if let (&PatKind::TupleStruct(ref qpath, ref pat_args, _),
408 &ExprMethodCall(ref method_path, _, ref method_args)) = (pat, &match_expr.node) {
409 let iter_expr = &method_args[0];
410 let lhs_constructor = last_path_segment(qpath);
411 if self.loop_count < 2 && method_path.name == "next" &&
412 match_trait_method(cx, match_expr, &paths::ITERATOR) &&
413 lhs_constructor.name == "Some" && !is_refutable(cx, &pat_args[0]) &&
414 !is_iterator_used_after_while_let(cx, iter_expr) {
415 let iterator = snippet(cx, method_args[0].span, "_");
416 let loop_var = snippet(cx, pat_args[0].span, "_");
417 span_lint_and_sugg(cx,
418 WHILE_LET_ON_ITERATOR,
420 "this loop could be written as a `for` loop",
422 format!("for {} in {} {{ .. }}", loop_var, iterator));
428 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
429 if let StmtSemi(ref expr, _) = stmt.node {
430 if let ExprMethodCall(ref method, _, ref args) = expr.node {
431 if args.len() == 1 && method.name == "collect" && match_trait_method(cx, expr, &paths::ITERATOR) {
435 "you are collect()ing an iterator and throwing away the result. \
436 Consider using an explicit for loop to exhaust the iterator");
443 fn never_loop(block: &Block, id: &NodeId) -> bool {
444 !contains_continue_block(block, id) && loop_exit_block(block)
447 fn contains_continue_block(block: &Block, dest: &NodeId) -> bool {
448 block.stmts.iter().any(|e| contains_continue_stmt(e, dest)) ||
449 block.expr.as_ref().map_or(false, |e| contains_continue_expr(e, dest))
452 fn contains_continue_stmt(stmt: &Stmt, dest: &NodeId) -> bool {
455 StmtExpr(ref e, _) => contains_continue_expr(e, dest),
456 StmtDecl(ref d, _) => contains_continue_decl(d, dest),
460 fn contains_continue_decl(decl: &Decl, dest: &NodeId) -> bool {
462 DeclLocal(ref local) => local.init.as_ref().map_or(false, |e| contains_continue_expr(e, dest)),
467 fn contains_continue_expr(expr: &Expr, dest: &NodeId) -> bool {
469 ExprRet(Some(ref e)) |
471 ExprUnary(_, ref e) |
474 ExprField(ref e, _) |
475 ExprTupField(ref e, _) |
476 ExprAddrOf(_, ref e) |
477 ExprRepeat(ref e, _) => contains_continue_expr(e, dest),
479 ExprMethodCall(_, _, ref es) |
480 ExprTup(ref es) => es.iter().any(|e| contains_continue_expr(e, dest)),
481 ExprCall(ref e, ref es) => {
482 contains_continue_expr(e, dest) || es.iter().any(|e| contains_continue_expr(e, dest))
484 ExprBinary(_, ref e1, ref e2) |
485 ExprAssign(ref e1, ref e2) |
486 ExprAssignOp(_, ref e1, ref e2) |
487 ExprIndex(ref e1, ref e2) => [e1, e2].iter().any(|e| contains_continue_expr(e, dest)),
488 ExprIf(ref e, ref e2, ref e3) => {
489 [e, e2].iter().chain(e3.as_ref().iter()).any(|e| contains_continue_expr(e, dest))
491 ExprWhile(ref e, ref b, _) => contains_continue_expr(e, dest) || contains_continue_block(b, dest),
492 ExprMatch(ref e, ref arms, _) => {
493 contains_continue_expr(e, dest) || arms.iter().any(|a| contains_continue_expr(&a.body, dest))
495 ExprBlock(ref block) => contains_continue_block(block, dest),
496 ExprStruct(_, _, ref base) => base.as_ref().map_or(false, |e| contains_continue_expr(e, dest)),
497 ExprAgain(d) => d.target_id.opt_id().map_or(false, |id| id == *dest),
502 fn loop_exit_block(block: &Block) -> bool {
503 block.stmts.iter().any(|e| loop_exit_stmt(e)) || block.expr.as_ref().map_or(false, |e| loop_exit_expr(e))
506 fn loop_exit_stmt(stmt: &Stmt) -> bool {
509 StmtExpr(ref e, _) => loop_exit_expr(e),
510 StmtDecl(ref d, _) => loop_exit_decl(d),
514 fn loop_exit_decl(decl: &Decl) -> bool {
516 DeclLocal(ref local) => local.init.as_ref().map_or(false, |e| loop_exit_expr(e)),
521 fn loop_exit_expr(expr: &Expr) -> bool {
524 ExprUnary(_, ref e) |
527 ExprField(ref e, _) |
528 ExprTupField(ref e, _) |
529 ExprAddrOf(_, ref e) |
530 ExprRepeat(ref e, _) => loop_exit_expr(e),
532 ExprMethodCall(_, _, ref es) |
533 ExprTup(ref es) => es.iter().any(|e| loop_exit_expr(e)),
534 ExprCall(ref e, ref es) => loop_exit_expr(e) || es.iter().any(|e| loop_exit_expr(e)),
535 ExprBinary(_, ref e1, ref e2) |
536 ExprAssign(ref e1, ref e2) |
537 ExprAssignOp(_, ref e1, ref e2) |
538 ExprIndex(ref e1, ref e2) => [e1, e2].iter().any(|e| loop_exit_expr(e)),
539 ExprIf(ref e, ref e2, ref e3) => {
540 loop_exit_expr(e) || e3.as_ref().map_or(false, |e| loop_exit_expr(e)) && loop_exit_expr(e2)
542 ExprWhile(ref e, ref b, _) => loop_exit_expr(e) || loop_exit_block(b),
543 ExprMatch(ref e, ref arms, _) => loop_exit_expr(e) || arms.iter().all(|a| loop_exit_expr(&a.body)),
544 ExprBlock(ref b) => loop_exit_block(b),
545 ExprBreak(_, _) | ExprAgain(_) | ExprRet(_) => true,
550 fn check_for_loop<'a, 'tcx>(
551 cx: &LateContext<'a, 'tcx>,
557 check_for_loop_range(cx, pat, arg, body, expr);
558 check_for_loop_reverse_range(cx, arg, expr);
559 check_for_loop_arg(cx, pat, arg, expr);
560 check_for_loop_explicit_counter(cx, arg, body, expr);
561 check_for_loop_over_map_kv(cx, pat, arg, body, expr);
564 /// Check for looping over a range and then indexing a sequence with it.
565 /// The iteratee must be a range literal.
566 fn check_for_loop_range<'a, 'tcx>(
567 cx: &LateContext<'a, 'tcx>,
573 if let Some(higher::Range { start: Some(start), ref end, limits }) = higher::range(arg) {
574 // the var must be a single name
575 if let PatKind::Binding(_, def_id, ref ident, _) = pat.node {
576 let mut visitor = VarVisitor {
579 indexed: HashMap::new(),
582 walk_expr(&mut visitor, body);
584 // linting condition: we only indexed one variable
585 if visitor.indexed.len() == 1 {
586 let (indexed, indexed_extent) = visitor.indexed
589 .unwrap_or_else(|| unreachable!() /* len == 1 */);
591 // ensure that the indexed variable was declared before the loop, see #601
592 if let Some(indexed_extent) = indexed_extent {
593 let parent_id = cx.tcx.hir.get_parent(expr.id);
594 let parent_def_id = cx.tcx.hir.local_def_id(parent_id);
595 let region_maps = cx.tcx.region_maps(parent_def_id);
596 let pat_extent = region_maps.var_scope(pat.id);
597 if region_maps.is_subscope_of(indexed_extent, pat_extent) {
602 let starts_at_zero = is_integer_literal(start, 0);
604 let skip = if starts_at_zero {
607 format!(".skip({})", snippet(cx, start.span, ".."))
610 let take = if let Some(end) = *end {
611 if is_len_call(end, &indexed) {
615 ast::RangeLimits::Closed => {
616 let end = sugg::Sugg::hir(cx, end, "<count>");
617 format!(".take({})", end + sugg::ONE)
619 ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, end.span, "..")),
626 if visitor.nonindex {
627 span_lint_and_then(cx,
630 &format!("the loop variable `{}` is used to index `{}`", ident.node, indexed),
633 "consider using an iterator".to_string(),
634 vec![(pat.span, format!("({}, <item>)", ident.node)),
635 (arg.span, format!("{}.iter().enumerate(){}{}", indexed, take, skip))]);
638 let repl = if starts_at_zero && take.is_empty() {
639 format!("&{}", indexed)
641 format!("{}.iter(){}{}", indexed, take, skip)
644 span_lint_and_then(cx,
647 &format!("the loop variable `{}` is only used to index `{}`.",
652 "consider using an iterator".to_string(),
653 vec![(pat.span, "<item>".to_string()), (arg.span, repl)]);
661 fn is_len_call(expr: &Expr, var: &Name) -> bool {
663 let ExprMethodCall(ref method, _, ref len_args) = expr.node,
665 method.name == "len",
666 let ExprPath(QPath::Resolved(_, ref path)) = len_args[0].node,
667 path.segments.len() == 1,
668 path.segments[0].name == *var
676 fn check_for_loop_reverse_range(cx: &LateContext, arg: &Expr, expr: &Expr) {
677 // if this for loop is iterating over a two-sided range...
678 if let Some(higher::Range { start: Some(start), end: Some(end), limits }) = higher::range(arg) {
679 // ...and both sides are compile-time constant integers...
680 let constcx = ConstContext::with_tables(cx.tcx, cx.tables);
681 if let Ok(start_idx) = constcx.eval(start) {
682 if let Ok(end_idx) = constcx.eval(end) {
683 // ...and the start index is greater than the end index,
684 // this loop will never run. This is often confusing for developers
685 // who think that this will iterate from the larger value to the
687 let (sup, eq) = match (start_idx, end_idx) {
688 (ConstVal::Integral(start_idx), ConstVal::Integral(end_idx)) => {
689 (start_idx > end_idx, start_idx == end_idx)
695 let start_snippet = snippet(cx, start.span, "_");
696 let end_snippet = snippet(cx, end.span, "_");
697 let dots = if limits == ast::RangeLimits::Closed {
703 span_lint_and_then(cx,
706 "this range is empty so this for loop will never run",
708 db.span_suggestion(arg.span,
709 "consider using the following if you are attempting to iterate over this \
711 format!("({end}{dots}{start}).rev()",
714 start = start_snippet));
716 } else if eq && limits != ast::RangeLimits::Closed {
717 // if they are equal, it's also problematic - this loop
722 "this range is empty so this for loop will never run");
729 fn lint_iter_method(cx: &LateContext, args: &[Expr], arg: &Expr, method_name: &str) {
730 let object = snippet(cx, args[0].span, "_");
731 let muta = if method_name == "iter_mut" {
736 span_lint_and_sugg(cx,
739 "it is more idiomatic to loop over references to containers instead of using explicit \
741 "to write this more concisely, try",
742 format!("&{}{}", muta, object))
745 fn check_for_loop_arg(cx: &LateContext, pat: &Pat, arg: &Expr, expr: &Expr) {
746 let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
747 if let ExprMethodCall(ref method, _, ref args) = arg.node {
748 // just the receiver, no arguments
750 let method_name = &*method.name.as_str();
751 // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
752 if method_name == "iter" || method_name == "iter_mut" {
753 if is_ref_iterable_type(cx, &args[0]) {
754 lint_iter_method(cx, args, arg, method_name);
756 } else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
757 let def_id = cx.tables.type_dependent_defs[&arg.id].def_id();
758 let substs = cx.tables.node_substs(arg.id);
759 let method_type = cx.tcx.type_of(def_id).subst(cx.tcx, substs);
761 let fn_arg_tys = method_type.fn_sig(cx.tcx).inputs();
762 assert_eq!(fn_arg_tys.skip_binder().len(), 1);
763 if fn_arg_tys.skip_binder()[0].is_region_ptr() {
764 lint_iter_method(cx, args, arg, method_name);
766 let object = snippet(cx, args[0].span, "_");
767 span_lint_and_sugg(cx,
768 EXPLICIT_INTO_ITER_LOOP,
770 "it is more idiomatic to loop over containers instead of using explicit \
772 "to write this more concisely, try",
775 } else if method_name == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
779 "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
780 probably not what you want");
781 next_loop_linted = true;
785 if !next_loop_linted {
786 check_arg_type(cx, pat, arg);
790 /// Check for `for` loops over `Option`s and `Results`
791 fn check_arg_type(cx: &LateContext, pat: &Pat, arg: &Expr) {
792 let ty = cx.tables.expr_ty(arg);
793 if match_type(cx, ty, &paths::OPTION) {
794 span_help_and_lint(cx,
795 FOR_LOOP_OVER_OPTION,
797 &format!("for loop over `{0}`, which is an `Option`. This is more readably written as an \
798 `if let` statement.",
799 snippet(cx, arg.span, "_")),
800 &format!("consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
801 snippet(cx, pat.span, "_"),
802 snippet(cx, arg.span, "_")));
803 } else if match_type(cx, ty, &paths::RESULT) {
804 span_help_and_lint(cx,
805 FOR_LOOP_OVER_RESULT,
807 &format!("for loop over `{0}`, which is a `Result`. This is more readably written as an \
808 `if let` statement.",
809 snippet(cx, arg.span, "_")),
810 &format!("consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
811 snippet(cx, pat.span, "_"),
812 snippet(cx, arg.span, "_")));
816 fn check_for_loop_explicit_counter<'a, 'tcx>(
817 cx: &LateContext<'a, 'tcx>,
822 // Look for variables that are incremented once per loop iteration.
823 let mut visitor = IncrementVisitor {
825 states: HashMap::new(),
829 walk_expr(&mut visitor, body);
831 // For each candidate, check the parent block to see if
832 // it's initialized to zero at the start of the loop.
833 let map = &cx.tcx.hir;
834 let parent_scope = map.get_enclosing_scope(expr.id).and_then(|id| map.get_enclosing_scope(id));
835 if let Some(parent_id) = parent_scope {
836 if let NodeBlock(block) = map.get(parent_id) {
837 for (id, _) in visitor.states.iter().filter(|&(_, v)| *v == VarState::IncrOnce) {
838 let mut visitor2 = InitializeVisitor {
842 state: VarState::IncrOnce,
847 walk_block(&mut visitor2, block);
849 if visitor2.state == VarState::Warn {
850 if let Some(name) = visitor2.name {
852 EXPLICIT_COUNTER_LOOP,
854 &format!("the variable `{0}` is used as a loop counter. Consider using `for ({0}, \
855 item) in {1}.enumerate()` or similar iterators",
857 snippet(cx, arg.span, "_")));
865 /// Check for the `FOR_KV_MAP` lint.
866 fn check_for_loop_over_map_kv<'a, 'tcx>(
867 cx: &LateContext<'a, 'tcx>,
873 let pat_span = pat.span;
875 if let PatKind::Tuple(ref pat, _) = pat.node {
877 let arg_span = arg.span;
878 let (new_pat_span, kind, ty, mutbl) = match cx.tables.expr_ty(arg).sty {
879 ty::TyRef(_, ref tam) => {
880 match (&pat[0].node, &pat[1].node) {
881 (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", tam.ty, tam.mutbl),
882 (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", tam.ty, MutImmutable),
888 let mutbl = match mutbl {
890 MutMutable => "_mut",
892 let arg = match arg.node {
893 ExprAddrOf(_, ref expr) => &**expr,
897 if match_type(cx, ty, &paths::HASHMAP) || match_type(cx, ty, &paths::BTREEMAP) {
898 span_lint_and_then(cx,
901 &format!("you seem to want to iterate on a map's {}s", kind),
903 let map = sugg::Sugg::hir(cx, arg, "map");
905 "use the corresponding method".into(),
906 vec![(pat_span, snippet(cx, new_pat_span, kind).into_owned()),
907 (arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl))]);
915 /// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`.
916 fn pat_is_wild<'tcx>(pat: &'tcx PatKind, body: &'tcx Expr) -> bool {
918 PatKind::Wild => true,
919 PatKind::Binding(_, _, ident, None) if ident.node.as_str().starts_with('_') => {
920 let mut visitor = UsedVisitor {
924 walk_expr(&mut visitor, body);
932 var: ast::Name, // var to look for
933 used: bool, // has the var been used otherwise?
936 impl<'tcx> Visitor<'tcx> for UsedVisitor {
937 fn visit_expr(&mut self, expr: &'tcx Expr) {
938 if let ExprPath(QPath::Resolved(None, ref path)) = expr.node {
939 if path.segments.len() == 1 && path.segments[0].name == self.var {
945 walk_expr(self, expr);
947 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
948 NestedVisitorMap::None
952 struct VarVisitor<'a, 'tcx: 'a> {
953 cx: &'a LateContext<'a, 'tcx>, // context reference
954 var: DefId, // var name to look for as index
955 indexed: HashMap<Name, Option<CodeExtent>>, // indexed variables, the extent is None for global
956 nonindex: bool, // has the var been used otherwise?
959 impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
960 fn visit_expr(&mut self, expr: &'tcx Expr) {
961 if let ExprPath(ref qpath) = expr.node {
962 if let QPath::Resolved(None, ref path) = *qpath {
963 if path.segments.len() == 1 && self.cx.tables.qpath_def(qpath, expr.id).def_id() == self.var {
964 // we are referencing our variable! now check if it's as an index
966 let Some(parexpr) = get_parent_expr(self.cx, expr),
967 let ExprIndex(ref seqexpr, _) = parexpr.node,
968 let ExprPath(ref seqpath) = seqexpr.node,
969 let QPath::Resolved(None, ref seqvar) = *seqpath,
970 seqvar.segments.len() == 1
972 let def = self.cx.tables.qpath_def(seqpath, seqexpr.id);
974 Def::Local(..) | Def::Upvar(..) => {
975 let def_id = def.def_id();
976 let node_id = self.cx.tcx.hir.as_local_node_id(def_id).expect("local/upvar are local nodes");
978 let parent_id = self.cx.tcx.hir.get_parent(expr.id);
979 let parent_def_id = self.cx.tcx.hir.local_def_id(parent_id);
980 let extent = self.cx.tcx.region_maps(parent_def_id).var_scope(node_id);
981 self.indexed.insert(seqvar.segments[0].name, Some(extent));
982 return; // no need to walk further
984 Def::Static(..) | Def::Const(..) => {
985 self.indexed.insert(seqvar.segments[0].name, None);
986 return; // no need to walk further
991 // we are not indexing anything, record that
992 self.nonindex = true;
997 walk_expr(self, expr);
999 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1000 NestedVisitorMap::None
1004 fn is_iterator_used_after_while_let<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, iter_expr: &'tcx Expr) -> bool {
1005 let def_id = match var_def_id(cx, iter_expr) {
1007 None => return false,
1009 let mut visitor = VarUsedAfterLoopVisitor {
1012 iter_expr_id: iter_expr.id,
1013 past_while_let: false,
1014 var_used_after_while_let: false,
1016 if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
1017 walk_block(&mut visitor, enclosing_block);
1019 visitor.var_used_after_while_let
1022 struct VarUsedAfterLoopVisitor<'a, 'tcx: 'a> {
1023 cx: &'a LateContext<'a, 'tcx>,
1025 iter_expr_id: NodeId,
1026 past_while_let: bool,
1027 var_used_after_while_let: bool,
1030 impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
1031 fn visit_expr(&mut self, expr: &'tcx Expr) {
1032 if self.past_while_let {
1033 if Some(self.def_id) == var_def_id(self.cx, expr) {
1034 self.var_used_after_while_let = true;
1036 } else if self.iter_expr_id == expr.id {
1037 self.past_while_let = true;
1039 walk_expr(self, expr);
1041 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1042 NestedVisitorMap::None
1047 /// Return true if the type of expr is one that provides `IntoIterator` impls
1048 /// for `&T` and `&mut T`, such as `Vec`.
1049 #[cfg_attr(rustfmt, rustfmt_skip)]
1050 fn is_ref_iterable_type(cx: &LateContext, e: &Expr) -> bool {
1051 // no walk_ptrs_ty: calling iter() on a reference can make sense because it
1052 // will allow further borrows afterwards
1053 let ty = cx.tables.expr_ty(e);
1054 is_iterable_array(ty) ||
1055 match_type(cx, ty, &paths::VEC) ||
1056 match_type(cx, ty, &paths::LINKED_LIST) ||
1057 match_type(cx, ty, &paths::HASHMAP) ||
1058 match_type(cx, ty, &paths::HASHSET) ||
1059 match_type(cx, ty, &paths::VEC_DEQUE) ||
1060 match_type(cx, ty, &paths::BINARY_HEAP) ||
1061 match_type(cx, ty, &paths::BTREEMAP) ||
1062 match_type(cx, ty, &paths::BTREESET)
1065 fn is_iterable_array(ty: Ty) -> bool {
1066 // IntoIterator is currently only implemented for array sizes <= 32 in rustc
1068 ty::TyArray(_, 0...32) => true,
1073 /// If a block begins with a statement (possibly a `let` binding) and has an expression, return it.
1074 fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
1075 if block.stmts.is_empty() {
1078 if let StmtDecl(ref decl, _) = block.stmts[0].node {
1079 if let DeclLocal(ref local) = decl.node {
1080 if let Some(ref expr) = local.init {
1093 /// If a block begins with an expression (with or without semicolon), return it.
1094 fn extract_first_expr(block: &Block) -> Option<&Expr> {
1096 Some(ref expr) if block.stmts.is_empty() => Some(expr),
1097 None if !block.stmts.is_empty() => {
1098 match block.stmts[0].node {
1099 StmtExpr(ref expr, _) |
1100 StmtSemi(ref expr, _) => Some(expr),
1101 StmtDecl(..) => None,
1108 /// Return true if expr contains a single break expr (maybe within a block).
1109 fn is_break_expr(expr: &Expr) -> bool {
1111 ExprBreak(dest, _) if dest.ident.is_none() => true,
1112 ExprBlock(ref b) => {
1113 match extract_first_expr(b) {
1114 Some(subexpr) => is_break_expr(subexpr),
1122 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
1123 // incremented exactly once in the loop body, and initialized to zero
1124 // at the start of the loop.
1125 #[derive(PartialEq)]
1127 Initial, // Not examined yet
1128 IncrOnce, // Incremented exactly once, may be a loop counter
1129 Declared, // Declared but not (yet) initialized to zero
1134 /// Scan a for loop for variables that are incremented exactly once.
1135 struct IncrementVisitor<'a, 'tcx: 'a> {
1136 cx: &'a LateContext<'a, 'tcx>, // context reference
1137 states: HashMap<NodeId, VarState>, // incremented variables
1138 depth: u32, // depth of conditional expressions
1142 impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
1143 fn visit_expr(&mut self, expr: &'tcx Expr) {
1148 // If node is a variable
1149 if let Some(def_id) = var_def_id(self.cx, expr) {
1150 if let Some(parent) = get_parent_expr(self.cx, expr) {
1151 let state = self.states.entry(def_id).or_insert(VarState::Initial);
1154 ExprAssignOp(op, ref lhs, ref rhs) => {
1155 if lhs.id == expr.id {
1156 if op.node == BiAdd && is_integer_literal(rhs, 1) {
1157 *state = match *state {
1158 VarState::Initial if self.depth == 0 => VarState::IncrOnce,
1159 _ => VarState::DontWarn,
1162 // Assigned some other value
1163 *state = VarState::DontWarn;
1167 ExprAssign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
1168 ExprAddrOf(mutability, _) if mutability == MutMutable => *state = VarState::DontWarn,
1172 } else if is_loop(expr) {
1173 self.states.clear();
1176 } else if is_conditional(expr) {
1178 walk_expr(self, expr);
1182 walk_expr(self, expr);
1184 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1185 NestedVisitorMap::None
1189 /// Check whether a variable is initialized to zero at the start of a loop.
1190 struct InitializeVisitor<'a, 'tcx: 'a> {
1191 cx: &'a LateContext<'a, 'tcx>, // context reference
1192 end_expr: &'tcx Expr, // the for loop. Stop scanning here.
1196 depth: u32, // depth of conditional expressions
1200 impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
1201 fn visit_decl(&mut self, decl: &'tcx Decl) {
1202 // Look for declarations of the variable
1203 if let DeclLocal(ref local) = decl.node {
1204 if local.pat.id == self.var_id {
1205 if let PatKind::Binding(_, _, ref ident, _) = local.pat.node {
1206 self.name = Some(ident.node);
1208 self.state = if let Some(ref init) = local.init {
1209 if is_integer_literal(init, 0) {
1220 walk_decl(self, decl);
1223 fn visit_expr(&mut self, expr: &'tcx Expr) {
1224 if self.state == VarState::DontWarn {
1227 if expr == self.end_expr {
1228 self.past_loop = true;
1231 // No need to visit expressions before the variable is
1233 if self.state == VarState::IncrOnce {
1237 // If node is the desired variable, see how it's used
1238 if var_def_id(self.cx, expr) == Some(self.var_id) {
1239 if let Some(parent) = get_parent_expr(self.cx, expr) {
1241 ExprAssignOp(_, ref lhs, _) if lhs.id == expr.id => {
1242 self.state = VarState::DontWarn;
1244 ExprAssign(ref lhs, ref rhs) if lhs.id == expr.id => {
1245 self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
1251 ExprAddrOf(mutability, _) if mutability == MutMutable => self.state = VarState::DontWarn,
1257 self.state = VarState::DontWarn;
1260 } else if !self.past_loop && is_loop(expr) {
1261 self.state = VarState::DontWarn;
1263 } else if is_conditional(expr) {
1265 walk_expr(self, expr);
1269 walk_expr(self, expr);
1271 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1272 NestedVisitorMap::None
1276 fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
1277 if let ExprPath(ref qpath) = expr.node {
1278 let path_res = cx.tables.qpath_def(qpath, expr.id);
1279 if let Def::Local(def_id) = path_res {
1280 let node_id = cx.tcx.hir.as_local_node_id(def_id).expect("That DefId should be valid");
1281 return Some(node_id);
1287 fn is_loop(expr: &Expr) -> bool {
1289 ExprLoop(..) | ExprWhile(..) => true,
1294 fn is_conditional(expr: &Expr) -> bool {
1296 ExprIf(..) | ExprMatch(..) => true,