1 use itertools::Itertools;
4 use rustc::hir::def::Def;
5 use rustc::hir::intravisit::{walk_block, walk_decl, walk_expr, walk_pat, walk_stmt, NestedVisitorMap, Visitor};
6 use rustc::hir::map::Node::{NodeBlock, NodeExpr, NodeStmt};
8 use rustc::middle::const_val::ConstVal;
9 use rustc::middle::region;
10 use rustc::middle::region::CodeExtent;
11 use rustc::middle::expr_use_visitor::*;
12 use rustc::middle::mem_categorization::cmt;
13 use rustc::ty::{self, Ty};
14 use rustc::ty::subst::{Subst, Substs};
15 use rustc_const_eval::ConstContext;
16 use std::collections::{HashMap, HashSet};
18 use syntax::codemap::Span;
20 use utils::const_to_u64;
22 use utils::{get_enclosing_block, get_parent_expr, higher, in_external_macro, is_integer_literal, is_refutable,
23 last_path_segment, match_trait_method, match_type, match_var, multispan_sugg, snippet, snippet_opt,
24 span_help_and_lint, span_lint, span_lint_and_sugg, span_lint_and_then};
27 /// **What it does:** Checks for for-loops that manually copy items between
28 /// slices that could be optimized by having a memcpy.
30 /// **Why is this bad?** It is not as fast as a memcpy.
32 /// **Known problems:** None.
36 /// for i in 0..src.len() {
37 /// dst[i + 64] = src[i];
43 "manually copying items between slices"
46 /// **What it does:** Checks for looping over the range of `0..len` of some
47 /// collection just to get the values by index.
49 /// **Why is this bad?** Just iterating the collection itself makes the intent
50 /// more clear and is probably faster.
52 /// **Known problems:** None.
56 /// for i in 0..vec.len() {
57 /// println!("{}", vec[i]);
61 pub NEEDLESS_RANGE_LOOP,
63 "for-looping over a range of indices where an iterator over items would do"
66 /// **What it does:** Checks for loops on `x.iter()` where `&x` will do, and
67 /// suggests the latter.
69 /// **Why is this bad?** Readability.
71 /// **Known problems:** False negatives. We currently only warn on some known
76 /// // with `y` a `Vec` or slice:
77 /// for x in y.iter() { .. }
80 pub EXPLICIT_ITER_LOOP,
82 "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
85 /// **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and
86 /// suggests the latter.
88 /// **Why is this bad?** Readability.
90 /// **Known problems:** None
94 /// // with `y` a `Vec` or slice:
95 /// for x in y.into_iter() { .. }
98 pub EXPLICIT_INTO_ITER_LOOP,
100 "for-looping over `_.into_iter()` when `_` would do"
103 /// **What it does:** Checks for loops on `x.next()`.
105 /// **Why is this bad?** `next()` returns either `Some(value)` if there was a
106 /// value, or `None` otherwise. The insidious thing is that `Option<_>`
107 /// implements `IntoIterator`, so that possibly one value will be iterated,
108 /// leading to some hard to find bugs. No one will want to write such code
109 /// [except to win an Underhanded Rust
110 /// Contest](https://www.reddit.
111 /// com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
113 /// **Known problems:** None.
117 /// for x in y.next() { .. }
122 "for-looping over `_.next()` which is probably not intended"
125 /// **What it does:** Checks for `for` loops over `Option` values.
127 /// **Why is this bad?** Readability. This is more clearly expressed as an `if
130 /// **Known problems:** None.
134 /// for x in option { .. }
139 /// if let Some(x) = option { .. }
142 pub FOR_LOOP_OVER_OPTION,
144 "for-looping over an `Option`, which is more clearly expressed as an `if let`"
147 /// **What it does:** Checks for `for` loops over `Result` values.
149 /// **Why is this bad?** Readability. This is more clearly expressed as an `if
152 /// **Known problems:** None.
156 /// for x in result { .. }
161 /// if let Ok(x) = result { .. }
164 pub FOR_LOOP_OVER_RESULT,
166 "for-looping over a `Result`, which is more clearly expressed as an `if let`"
169 /// **What it does:** Detects `loop + match` combinations that are easier
170 /// written as a `while let` loop.
172 /// **Why is this bad?** The `while let` loop is usually shorter and more
175 /// **Known problems:** Sometimes the wrong binding is displayed (#383).
180 /// let x = match y {
184 /// // .. do something with x
186 /// // is easier written as
187 /// while let Some(x) = y {
188 /// // .. do something with x
194 "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
197 /// **What it does:** Checks for using `collect()` on an iterator without using
200 /// **Why is this bad?** It is more idiomatic to use a `for` loop over the
201 /// iterator instead.
203 /// **Known problems:** None.
207 /// vec.iter().map(|x| /* some operation returning () */).collect::<Vec<_>>();
212 "`collect()`ing an iterator without using the result; this is usually better \
213 written as a for loop"
216 /// **What it does:** Checks for loops over ranges `x..y` where both `x` and `y`
217 /// are constant and `x` is greater or equal to `y`, unless the range is
218 /// reversed or has a negative `.step_by(_)`.
220 /// **Why is it bad?** Such loops will either be skipped or loop until
221 /// wrap-around (in debug code, this may `panic!()`). Both options are probably
224 /// **Known problems:** The lint cannot catch loops over dynamically defined
225 /// ranges. Doing this would require simulating all possible inputs and code
226 /// paths through the program, which would be complex and error-prone.
230 /// for x in 5..10-5 { .. } // oops, stray `-`
233 pub REVERSE_RANGE_LOOP,
235 "iteration over an empty range, such as `10..0` or `5..5`"
238 /// **What it does:** Checks `for` loops over slices with an explicit counter
239 /// and suggests the use of `.enumerate()`.
241 /// **Why is it bad?** Not only is the version using `.enumerate()` more
242 /// readable, the compiler is able to remove bounds checks which can lead to
243 /// faster code in some instances.
245 /// **Known problems:** None.
249 /// for i in 0..v.len() { foo(v[i]);
250 /// for i in 0..v.len() { bar(i, v[i]); }
253 pub EXPLICIT_COUNTER_LOOP,
255 "for-looping with an explicit counter when `_.enumerate()` would do"
258 /// **What it does:** Checks for empty `loop` expressions.
260 /// **Why is this bad?** Those busy loops burn CPU cycles without doing
261 /// anything. Think of the environment and either block on something or at least
262 /// make the thread sleep for some microseconds.
264 /// **Known problems:** None.
273 "empty `loop {}`, which should block or sleep"
276 /// **What it does:** Checks for `while let` expressions on iterators.
278 /// **Why is this bad?** Readability. A simple `for` loop is shorter and conveys
279 /// the intent better.
281 /// **Known problems:** None.
285 /// while let Some(val) = iter() { .. }
288 pub WHILE_LET_ON_ITERATOR,
290 "using a while-let loop instead of a for loop on an iterator"
293 /// **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and
294 /// ignoring either the keys or values.
296 /// **Why is this bad?** Readability. There are `keys` and `values` methods that
297 /// can be used to express that don't need the values or keys.
299 /// **Known problems:** None.
303 /// for (k, _) in &map { .. }
306 /// could be replaced by
309 /// for k in map.keys() { .. }
314 "looping on a map using `iter` when `keys` or `values` would do"
317 /// **What it does:** Checks for loops that will always `break`, `return` or
318 /// `continue` an outer loop.
320 /// **Why is this bad?** This loop never loops, all it does is obfuscating the
323 /// **Known problems:** None
327 /// loop { ..; break; }
332 "any loop that will always `break` or `return`"
335 /// TODO: add documentation
340 "for loop over a range where one of the bounds is a mutable variable"
343 #[derive(Copy, Clone)]
346 impl LintPass for Pass {
347 fn get_lints(&self) -> LintArray {
352 EXPLICIT_INTO_ITER_LOOP,
354 FOR_LOOP_OVER_RESULT,
355 FOR_LOOP_OVER_OPTION,
359 EXPLICIT_COUNTER_LOOP,
361 WHILE_LET_ON_ITERATOR,
369 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
370 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
371 if let Some((pat, arg, body)) = higher::for_loop(expr) {
372 check_for_loop(cx, pat, arg, body, expr);
375 // check for never_loop
377 ExprWhile(_, ref block, _) |
378 ExprLoop(ref block, _, _) => {
379 if never_loop(block, &expr.id) {
380 span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops");
386 // check for `loop { if let {} else break }` that could be `while let`
387 // (also matches an explicit "match" instead of "if let")
388 // (even if the "match" or "if let" is used for declaration)
389 if let ExprLoop(ref block, _, LoopSource::Loop) = expr.node {
390 // also check for empty `loop {}` statements
391 if block.stmts.is_empty() && block.expr.is_none() {
396 "empty `loop {}` detected. You may want to either use `panic!()` or add \
397 `std::thread::sleep(..);` to the loop body.",
401 // extract the expression from the first statement (if any) in a block
402 let inner_stmt_expr = extract_expr_from_first_stmt(block);
403 // or extract the first expression (if any) from the block
404 if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
405 if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node {
406 // ensure "if let" compatible match structure
408 MatchSource::Normal |
409 MatchSource::IfLetDesugar { .. } => {
410 if arms.len() == 2 && arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
411 arms[1].pats.len() == 1 && arms[1].guard.is_none() &&
412 is_simple_break_expr(&arms[1].body)
414 if in_external_macro(cx, expr.span) {
418 // NOTE: we used to make build a body here instead of using
419 // ellipsis, this was removed because:
420 // 1) it was ugly with big bodies;
421 // 2) it was not indented properly;
422 // 3) it wasn’t very smart (see #675).
427 "this loop could be written as a `while let` loop",
430 "while let {} = {} {{ .. }}",
431 snippet(cx, arms[0].pats[0].span, ".."),
432 snippet(cx, matchexpr.span, "..")
442 if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
443 let pat = &arms[0].pats[0].node;
444 if let (&PatKind::TupleStruct(ref qpath, ref pat_args, _),
445 &ExprMethodCall(ref method_path, _, ref method_args)) = (pat, &match_expr.node)
447 let iter_expr = &method_args[0];
448 let lhs_constructor = last_path_segment(qpath);
449 if method_path.name == "next" && match_trait_method(cx, match_expr, &paths::ITERATOR) &&
450 lhs_constructor.name == "Some" && !is_refutable(cx, &pat_args[0]) &&
451 !is_iterator_used_after_while_let(cx, iter_expr) &&
452 !is_nested(cx, expr, &method_args[0])
454 let iterator = snippet(cx, method_args[0].span, "_");
455 let loop_var = snippet(cx, pat_args[0].span, "_");
458 WHILE_LET_ON_ITERATOR,
460 "this loop could be written as a `for` loop",
462 format!("for {} in {} {{ .. }}", loop_var, iterator),
469 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
470 if let StmtSemi(ref expr, _) = stmt.node {
471 if let ExprMethodCall(ref method, _, ref args) = expr.node {
472 if args.len() == 1 && method.name == "collect" && match_trait_method(cx, expr, &paths::ITERATOR) {
477 "you are collect()ing an iterator and throwing away the result. \
478 Consider using an explicit for loop to exhaust the iterator",
486 fn never_loop(block: &Block, id: &NodeId) -> bool {
487 !contains_continue_block(block, id) && loop_exit_block(block)
490 fn contains_continue_block(block: &Block, dest: &NodeId) -> bool {
491 block.stmts.iter().any(|e| contains_continue_stmt(e, dest)) ||
492 block.expr.as_ref().map_or(
494 |e| contains_continue_expr(e, dest),
498 fn contains_continue_stmt(stmt: &Stmt, dest: &NodeId) -> bool {
501 StmtExpr(ref e, _) => contains_continue_expr(e, dest),
502 StmtDecl(ref d, _) => contains_continue_decl(d, dest),
506 fn contains_continue_decl(decl: &Decl, dest: &NodeId) -> bool {
508 DeclLocal(ref local) => {
509 local.init.as_ref().map_or(
511 |e| contains_continue_expr(e, dest),
518 fn contains_continue_expr(expr: &Expr, dest: &NodeId) -> bool {
520 ExprRet(Some(ref e)) |
522 ExprUnary(_, ref e) |
525 ExprField(ref e, _) |
526 ExprTupField(ref e, _) |
527 ExprAddrOf(_, ref e) |
528 ExprRepeat(ref e, _) => contains_continue_expr(e, dest),
530 ExprMethodCall(_, _, ref es) |
531 ExprTup(ref es) => es.iter().any(|e| contains_continue_expr(e, dest)),
532 ExprCall(ref e, ref es) => {
533 contains_continue_expr(e, dest) || es.iter().any(|e| contains_continue_expr(e, dest))
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| contains_continue_expr(e, dest)),
539 ExprIf(ref e, ref e2, ref e3) => {
540 [e, e2].iter().chain(e3.as_ref().iter()).any(|e| {
541 contains_continue_expr(e, dest)
544 ExprWhile(ref e, ref b, _) => contains_continue_expr(e, dest) || contains_continue_block(b, dest),
545 ExprMatch(ref e, ref arms, _) => {
546 contains_continue_expr(e, dest) || arms.iter().any(|a| contains_continue_expr(&a.body, dest))
548 ExprBlock(ref block) |
549 ExprLoop(ref block, ..) => contains_continue_block(block, dest),
550 ExprStruct(_, _, ref base) => {
551 base.as_ref().map_or(
553 |e| contains_continue_expr(e, dest),
556 ExprAgain(d) => d.target_id.opt_id().map_or(false, |id| id == *dest),
561 fn loop_exit_block(block: &Block) -> bool {
562 block.stmts.iter().any(|e| loop_exit_stmt(e)) || block.expr.as_ref().map_or(false, |e| loop_exit_expr(e))
565 fn loop_exit_stmt(stmt: &Stmt) -> bool {
568 StmtExpr(ref e, _) => loop_exit_expr(e),
569 StmtDecl(ref d, _) => loop_exit_decl(d),
573 fn loop_exit_decl(decl: &Decl) -> bool {
575 DeclLocal(ref local) => local.init.as_ref().map_or(false, |e| loop_exit_expr(e)),
580 fn loop_exit_expr(expr: &Expr) -> bool {
583 ExprUnary(_, ref e) |
586 ExprField(ref e, _) |
587 ExprTupField(ref e, _) |
588 ExprAddrOf(_, ref e) |
589 ExprRepeat(ref e, _) => loop_exit_expr(e),
591 ExprMethodCall(_, _, ref es) |
592 ExprTup(ref es) => es.iter().any(|e| loop_exit_expr(e)),
593 ExprCall(ref e, ref es) => loop_exit_expr(e) || es.iter().any(|e| loop_exit_expr(e)),
594 ExprBinary(_, ref e1, ref e2) |
595 ExprAssign(ref e1, ref e2) |
596 ExprAssignOp(_, ref e1, ref e2) |
597 ExprIndex(ref e1, ref e2) => [e1, e2].iter().any(|e| loop_exit_expr(e)),
598 ExprIf(ref e, ref e2, ref e3) => {
599 loop_exit_expr(e) || e3.as_ref().map_or(false, |e| loop_exit_expr(e)) && loop_exit_expr(e2)
601 ExprWhile(ref e, ref b, _) => loop_exit_expr(e) || loop_exit_block(b),
602 ExprMatch(ref e, ref arms, _) => loop_exit_expr(e) || arms.iter().all(|a| loop_exit_expr(&a.body)),
603 ExprBlock(ref b) => loop_exit_block(b),
604 ExprBreak(_, _) | ExprAgain(_) | ExprRet(_) => true,
609 fn check_for_loop<'a, 'tcx>(
610 cx: &LateContext<'a, 'tcx>,
616 check_for_loop_range(cx, pat, arg, body, expr);
617 check_for_loop_reverse_range(cx, arg, expr);
618 check_for_loop_arg(cx, pat, arg, expr);
619 check_for_loop_explicit_counter(cx, arg, body, expr);
620 check_for_loop_over_map_kv(cx, pat, arg, body, expr);
621 check_for_mut_range_bound(cx, arg, body, expr);
622 detect_manual_memcpy(cx, pat, arg, body, expr);
625 fn same_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr, var: ast::NodeId) -> bool {
627 let ExprPath(ref qpath) = expr.node,
628 let QPath::Resolved(None, ref path) = *qpath,
629 path.segments.len() == 1,
630 let Def::Local(local_id) = cx.tables.qpath_def(qpath, expr.hir_id),
646 fn negative(s: String) -> Self {
653 fn positive(s: String) -> Self {
661 struct FixedOffsetVar {
666 fn is_slice_like<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty) -> bool {
667 let is_slice = match ty.sty {
668 ty::TyRef(_, ref subty) => is_slice_like(cx, subty.ty),
669 ty::TySlice(..) | ty::TyArray(..) => true,
673 is_slice || match_type(cx, ty, &paths::VEC) || match_type(cx, ty, &paths::VEC_DEQUE)
676 fn get_fixed_offset_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr, var: ast::NodeId) -> Option<FixedOffsetVar> {
677 fn extract_offset<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &Expr, var: ast::NodeId) -> Option<String> {
681 ast::LitKind::Int(x, _ty) => Some(x.to_string()),
685 ExprPath(..) if !same_var(cx, e, var) => Some(snippet_opt(cx, e.span).unwrap_or_else(|| "??".into())),
690 if let ExprIndex(ref seqexpr, ref idx) = expr.node {
691 let ty = cx.tables.expr_ty(seqexpr);
692 if !is_slice_like(cx, ty) {
696 let offset = match idx.node {
697 ExprBinary(op, ref lhs, ref rhs) => {
700 let offset_opt = if same_var(cx, lhs, var) {
701 extract_offset(cx, rhs, var)
702 } else if same_var(cx, rhs, var) {
703 extract_offset(cx, lhs, var)
708 offset_opt.map(Offset::positive)
710 BinOp_::BiSub if same_var(cx, lhs, var) => extract_offset(cx, rhs, var).map(Offset::negative),
715 if same_var(cx, idx, var) {
716 Some(Offset::positive("0".into()))
726 var_name: snippet_opt(cx, seqexpr.span).unwrap_or_else(|| "???".into()),
735 fn fetch_cloned_fixed_offset_var<'a, 'tcx>(
736 cx: &LateContext<'a, 'tcx>,
739 ) -> Option<FixedOffsetVar> {
741 let ExprMethodCall(ref method, _, ref args) = expr.node,
742 method.name == "clone",
744 let Some(arg) = args.get(0),
746 return get_fixed_offset_var(cx, arg, var);
749 get_fixed_offset_var(cx, expr, var)
752 fn get_indexed_assignments<'a, 'tcx>(
753 cx: &LateContext<'a, 'tcx>,
756 ) -> Vec<(FixedOffsetVar, FixedOffsetVar)> {
757 fn get_assignment<'a, 'tcx>(
758 cx: &LateContext<'a, 'tcx>,
761 ) -> Option<(FixedOffsetVar, FixedOffsetVar)> {
762 if let Expr_::ExprAssign(ref lhs, ref rhs) = e.node {
763 match (get_fixed_offset_var(cx, lhs, var), fetch_cloned_fixed_offset_var(cx, rhs, var)) {
764 (Some(offset_left), Some(offset_right)) => Some((offset_left, offset_right)),
772 if let Expr_::ExprBlock(ref b) = body.node {
781 .map(|stmt| match stmt.node {
782 Stmt_::StmtDecl(..) => None,
783 Stmt_::StmtExpr(ref e, _node_id) |
784 Stmt_::StmtSemi(ref e, _node_id) => Some(get_assignment(cx, e, var)),
786 .chain(expr.as_ref().into_iter().map(|e| {
787 Some(get_assignment(cx, &*e, var))
790 .collect::<Option<Vec<_>>>()
791 .unwrap_or_else(|| vec![])
793 get_assignment(cx, body, var).into_iter().collect()
797 /// Check for for loops that sequentially copy items from one slice-like
798 /// object to another.
799 fn detect_manual_memcpy<'a, 'tcx>(
800 cx: &LateContext<'a, 'tcx>,
806 if let Some(higher::Range {
810 }) = higher::range(arg)
812 // the var must be a single name
813 if let PatKind::Binding(_, canonical_id, _, _) = pat.node {
814 let print_sum = |arg1: &Offset, arg2: &Offset| -> String {
815 match (&arg1.value[..], arg1.negate, &arg2.value[..], arg2.negate) {
816 ("0", _, "0", _) => "".into(),
818 (x, false, "0", false) => x.into(),
820 (x, false, "0", true) => format!("-{}", x),
821 (x, false, y, false) => format!("({} + {})", x, y),
822 (x, false, y, true) => format!("({} - {})", x, y),
823 (x, true, y, false) => format!("({} - {})", y, x),
824 (x, true, y, true) => format!("-({} + {})", x, y),
828 let print_limit = |end: &Option<&Expr>, offset: Offset, var_name: &str| if let Some(end) = *end {
830 let ExprMethodCall(ref method, _, ref len_args) = end.node,
831 method.name == "len",
833 let Some(arg) = len_args.get(0),
834 snippet(cx, arg.span, "??") == var_name,
836 return if offset.negate {
837 format!("({} - {})", snippet(cx, end.span, "<src>.len()"), offset.value)
843 let end_str = match limits {
844 ast::RangeLimits::Closed => {
845 let end = sugg::Sugg::hir(cx, end, "<count>");
846 format!("{}", end + sugg::ONE)
848 ast::RangeLimits::HalfOpen => format!("{}", snippet(cx, end.span, "..")),
851 print_sum(&Offset::positive(end_str), &offset)
856 // The only statements in the for loops can be indexed assignments from
857 // indexed retrievals.
858 let manual_copies = get_indexed_assignments(cx, body, canonical_id);
860 let big_sugg = manual_copies
862 .map(|(dst_var, src_var)| {
863 let start_str = Offset::positive(snippet_opt(cx, start.span).unwrap_or_else(|| "".into()));
864 let dst_offset = print_sum(&start_str, &dst_var.offset);
865 let dst_limit = print_limit(end, dst_var.offset, &dst_var.var_name);
866 let src_offset = print_sum(&start_str, &src_var.offset);
867 let src_limit = print_limit(end, src_var.offset, &src_var.var_name);
868 let dst = if dst_offset == "" && dst_limit == "" {
871 format!("{}[{}..{}]", dst_var.var_name, dst_offset, dst_limit)
874 format!("{}.clone_from_slice(&{}[{}..{}])", dst, src_var.var_name, src_offset, src_limit)
878 if !big_sugg.is_empty() {
883 "it looks like you're manually copying between slices",
884 "try replacing the loop by",
892 /// Check for looping over a range and then indexing a sequence with it.
893 /// The iteratee must be a range literal.
894 fn check_for_loop_range<'a, 'tcx>(
895 cx: &LateContext<'a, 'tcx>,
901 if let Some(higher::Range {
905 }) = higher::range(arg)
907 // the var must be a single name
908 if let PatKind::Binding(_, canonical_id, ref ident, _) = pat.node {
909 let mut visitor = VarVisitor {
912 indexed: HashMap::new(),
913 referenced: HashSet::new(),
916 walk_expr(&mut visitor, body);
918 // linting condition: we only indexed one variable
919 if visitor.indexed.len() == 1 {
920 let (indexed, indexed_extent) = visitor.indexed.into_iter().next().expect(
921 "already checked that we have exactly 1 element",
924 // ensure that the indexed variable was declared before the loop, see #601
925 if let Some(indexed_extent) = indexed_extent {
926 let parent_id = cx.tcx.hir.get_parent(expr.id);
927 let parent_def_id = cx.tcx.hir.local_def_id(parent_id);
928 let region_scope_tree = cx.tcx.region_scope_tree(parent_def_id);
929 let pat_extent = region_scope_tree.var_scope(pat.hir_id.local_id);
930 if region_scope_tree.is_subscope_of(indexed_extent, pat_extent) {
935 // don't lint if the container that is indexed into is also used without
937 if visitor.referenced.contains(&indexed) {
941 let starts_at_zero = is_integer_literal(start, 0);
943 let skip = if starts_at_zero {
946 format!(".skip({})", snippet(cx, start.span, ".."))
949 let take = if let Some(end) = *end {
950 if is_len_call(end, &indexed) {
954 ast::RangeLimits::Closed => {
955 let end = sugg::Sugg::hir(cx, end, "<count>");
956 format!(".take({})", end + sugg::ONE)
958 ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, end.span, "..")),
965 if visitor.nonindex {
970 &format!("the loop variable `{}` is used to index `{}`", ident.node, indexed),
974 "consider using an iterator".to_string(),
976 (pat.span, format!("({}, <item>)", ident.node)),
977 (arg.span, format!("{}.iter().enumerate(){}{}", indexed, take, skip)),
983 let repl = if starts_at_zero && take.is_empty() {
984 format!("&{}", indexed)
986 format!("{}.iter(){}{}", indexed, take, skip)
993 &format!("the loop variable `{}` is only used to index `{}`.", ident.node, indexed),
997 "consider using an iterator".to_string(),
998 vec![(pat.span, "<item>".to_string()), (arg.span, repl)],
1008 fn is_len_call(expr: &Expr, var: &Name) -> bool {
1010 let ExprMethodCall(ref method, _, ref len_args) = expr.node,
1011 len_args.len() == 1,
1012 method.name == "len",
1013 let ExprPath(QPath::Resolved(_, ref path)) = len_args[0].node,
1014 path.segments.len() == 1,
1015 path.segments[0].name == *var
1023 fn check_for_loop_reverse_range<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arg: &'tcx Expr, expr: &'tcx Expr) {
1024 // if this for loop is iterating over a two-sided range...
1025 if let Some(higher::Range {
1029 }) = higher::range(arg)
1031 // ...and both sides are compile-time constant integers...
1032 let parent_item = cx.tcx.hir.get_parent(arg.id);
1033 let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
1034 let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
1035 let constcx = ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables);
1036 if let Ok(start_idx) = constcx.eval(start) {
1037 if let Ok(end_idx) = constcx.eval(end) {
1038 // ...and the start index is greater than the end index,
1039 // this loop will never run. This is often confusing for developers
1040 // who think that this will iterate from the larger value to the
1042 let (sup, eq) = match (start_idx, end_idx) {
1043 (&ty::Const { val: ConstVal::Integral(start_idx), .. },
1044 &ty::Const { val: ConstVal::Integral(end_idx), .. }) => {
1045 (start_idx > end_idx, start_idx == end_idx)
1047 _ => (false, false),
1051 let start_snippet = snippet(cx, start.span, "_");
1052 let end_snippet = snippet(cx, end.span, "_");
1053 let dots = if limits == ast::RangeLimits::Closed {
1063 "this range is empty so this for loop will never run",
1067 "consider using the following if you are attempting to iterate over this \
1070 "({end}{dots}{start}).rev()",
1073 start = start_snippet
1078 } else if eq && limits != ast::RangeLimits::Closed {
1079 // if they are equal, it's also problematic - this loop
1085 "this range is empty so this for loop will never run",
1093 fn lint_iter_method(cx: &LateContext, args: &[Expr], arg: &Expr, method_name: &str) {
1094 let object = snippet(cx, args[0].span, "_");
1095 let muta = if method_name == "iter_mut" {
1104 "it is more idiomatic to loop over references to containers instead of using explicit \
1106 "to write this more concisely, try",
1107 format!("&{}{}", muta, object),
1111 fn check_for_loop_arg(cx: &LateContext, pat: &Pat, arg: &Expr, expr: &Expr) {
1112 let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
1113 if let ExprMethodCall(ref method, _, ref args) = arg.node {
1114 // just the receiver, no arguments
1115 if args.len() == 1 {
1116 let method_name = &*method.name.as_str();
1117 // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
1118 if method_name == "iter" || method_name == "iter_mut" {
1119 if is_ref_iterable_type(cx, &args[0]) {
1120 lint_iter_method(cx, args, arg, method_name);
1122 } else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
1123 let def_id = cx.tables.type_dependent_defs()[arg.hir_id].def_id();
1124 let substs = cx.tables.node_substs(arg.hir_id);
1125 let method_type = cx.tcx.type_of(def_id).subst(cx.tcx, substs);
1127 let fn_arg_tys = method_type.fn_sig(cx.tcx).inputs();
1128 assert_eq!(fn_arg_tys.skip_binder().len(), 1);
1129 if fn_arg_tys.skip_binder()[0].is_region_ptr() {
1130 lint_iter_method(cx, args, arg, method_name);
1132 let object = snippet(cx, args[0].span, "_");
1135 EXPLICIT_INTO_ITER_LOOP,
1137 "it is more idiomatic to loop over containers instead of using explicit \
1138 iteration methods`",
1139 "to write this more concisely, try",
1143 } else if method_name == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
1148 "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
1149 probably not what you want",
1151 next_loop_linted = true;
1155 if !next_loop_linted {
1156 check_arg_type(cx, pat, arg);
1160 /// Check for `for` loops over `Option`s and `Results`
1161 fn check_arg_type(cx: &LateContext, pat: &Pat, arg: &Expr) {
1162 let ty = cx.tables.expr_ty(arg);
1163 if match_type(cx, ty, &paths::OPTION) {
1166 FOR_LOOP_OVER_OPTION,
1169 "for loop over `{0}`, which is an `Option`. This is more readably written as an \
1170 `if let` statement.",
1171 snippet(cx, arg.span, "_")
1174 "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
1175 snippet(cx, pat.span, "_"),
1176 snippet(cx, arg.span, "_")
1179 } else if match_type(cx, ty, &paths::RESULT) {
1182 FOR_LOOP_OVER_RESULT,
1185 "for loop over `{0}`, which is a `Result`. This is more readably written as an \
1186 `if let` statement.",
1187 snippet(cx, arg.span, "_")
1190 "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
1191 snippet(cx, pat.span, "_"),
1192 snippet(cx, arg.span, "_")
1198 fn check_for_loop_explicit_counter<'a, 'tcx>(
1199 cx: &LateContext<'a, 'tcx>,
1204 // Look for variables that are incremented once per loop iteration.
1205 let mut visitor = IncrementVisitor {
1207 states: HashMap::new(),
1211 walk_expr(&mut visitor, body);
1213 // For each candidate, check the parent block to see if
1214 // it's initialized to zero at the start of the loop.
1215 let map = &cx.tcx.hir;
1216 let parent_scope = map.get_enclosing_scope(expr.id).and_then(|id| {
1217 map.get_enclosing_scope(id)
1219 if let Some(parent_id) = parent_scope {
1220 if let NodeBlock(block) = map.get(parent_id) {
1221 for (id, _) in visitor.states.iter().filter(
1222 |&(_, v)| *v == VarState::IncrOnce,
1225 let mut visitor2 = InitializeVisitor {
1229 state: VarState::IncrOnce,
1234 walk_block(&mut visitor2, block);
1236 if visitor2.state == VarState::Warn {
1237 if let Some(name) = visitor2.name {
1240 EXPLICIT_COUNTER_LOOP,
1243 "the variable `{0}` is used as a loop counter. Consider using `for ({0}, \
1244 item) in {1}.enumerate()` or similar iterators",
1246 snippet(cx, arg.span, "_")
1256 /// Check for the `FOR_KV_MAP` lint.
1257 fn check_for_loop_over_map_kv<'a, 'tcx>(
1258 cx: &LateContext<'a, 'tcx>,
1264 let pat_span = pat.span;
1266 if let PatKind::Tuple(ref pat, _) = pat.node {
1268 let arg_span = arg.span;
1269 let (new_pat_span, kind, ty, mutbl) = match cx.tables.expr_ty(arg).sty {
1270 ty::TyRef(_, ref tam) => {
1271 match (&pat[0].node, &pat[1].node) {
1272 (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", tam.ty, tam.mutbl),
1273 (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", tam.ty, MutImmutable),
1279 let mutbl = match mutbl {
1281 MutMutable => "_mut",
1283 let arg = match arg.node {
1284 ExprAddrOf(_, ref expr) => &**expr,
1288 if match_type(cx, ty, &paths::HASHMAP) || match_type(cx, ty, &paths::BTREEMAP) {
1293 &format!("you seem to want to iterate on a map's {}s", kind),
1295 let map = sugg::Sugg::hir(cx, arg, "map");
1298 "use the corresponding method".into(),
1300 (pat_span, snippet(cx, new_pat_span, kind).into_owned()),
1301 (arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)),
1311 // TODO: clippy builds, but the `mutate` method of `Delegate` is never called when compiling `tests/run-pass/mut_range_bound_tmp.rs`. what's wrong?
1313 struct MutateDelegate<'a, 'tcx: 'a> {
1314 cx: &'a LateContext<'a, 'tcx>,
1319 impl<'a, 'tcx> Delegate<'tcx> for MutateDelegate<'a, 'tcx> {
1320 fn consume(&mut self, _: NodeId, _: Span, cmt: cmt<'tcx>, mode: ConsumeMode) {
1323 fn matched_pat(&mut self, matched_pat: &Pat, cmt: cmt<'tcx>, mode: MatchMode) {
1326 fn consume_pat(&mut self, consume_pat: &Pat, cmt: cmt<'tcx>, mode: ConsumeMode) {
1329 fn borrow(&mut self, _: NodeId, _: Span, _: cmt<'tcx>, _: ty::Region, _: ty::BorrowKind, _: LoanCause) {
1332 fn mutate(&mut self, assignment_id: NodeId, _: Span, _: cmt<'tcx>, _: MutateMode) {
1333 println!("something was mutated"); // tmp: see if this function is ever called at all (no)
1334 if assignment_id == self.node_id {
1335 self.was_mutated = true;
1339 fn decl_without_init(&mut self, _: NodeId, _: Span) {
1343 impl<'a, 'tcx> MutateDelegate<'a, 'tcx> {
1344 fn bound_was_mutated(&self) -> bool {
1349 fn check_for_mut_range_bound(cx: &LateContext, arg: &Expr, body: &Expr, expr: &Expr) {
1350 if let Some(higher::Range { start: Some(start), end: Some(end), limits }) = higher::range(arg) {
1351 let bounds = vec![start, end];
1352 for bound in &bounds {
1353 if check_for_mutation(cx, body, bound) {
1354 span_lint(cx, MUT_RANGE_BOUND, expr.span, "you are looping over a range where at least one bound was defined as a mutable variable. keep in mind that mutating this variable inside the loop will not affect the range");
1361 fn check_for_mutation(cx: &LateContext, body: &Expr, bound: &Expr) -> bool {
1363 let ExprPath(ref qpath) = bound.node,
1364 let QPath::Resolved(None, ref path) = *qpath,
1366 let def = cx.tables.qpath_def(qpath, bound.hir_id);
1368 Def::Local(..) | Def::Upvar(..) => {
1369 let def_id = def.def_id();
1370 let node_id = cx.tcx.hir.as_local_node_id(def_id).expect("local/upvar are local nodes");
1371 let node_str = cx.tcx.hir.get(node_id);
1372 if_let_chain! {[ // prob redundant now, remove
1373 let map::Node::NodeLocal(local) = node_str,
1374 let PatKind::Binding(bind_ann, _, _, _) = local.pat.node,
1375 let BindingAnnotation::Mutable = bind_ann,
1378 println!("bound was mutable"); // tmp: make sure the full if-let chain executes when it should (yes)
1379 let mut delegate = MutateDelegate { cx: cx, node_id: node_id, was_mutated: false };
1380 let region_maps = &cx.tcx.region_maps(def_id); // is this the correct argument?
1381 ExprUseVisitor::new(&mut delegate, cx.tcx, cx.param_env, region_maps, cx.tables).walk_expr(body);
1382 return delegate.bound_was_mutated();
1391 /// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`.
1392 fn pat_is_wild<'tcx>(pat: &'tcx PatKind, body: &'tcx Expr) -> bool {
1394 PatKind::Wild => true,
1395 PatKind::Binding(_, _, ident, None) if ident.node.as_str().starts_with('_') => {
1396 let mut visitor = UsedVisitor {
1400 walk_expr(&mut visitor, body);
1407 struct UsedVisitor {
1408 var: ast::Name, // var to look for
1409 used: bool, // has the var been used otherwise?
1412 impl<'tcx> Visitor<'tcx> for UsedVisitor {
1413 fn visit_expr(&mut self, expr: &'tcx Expr) {
1414 if match_var(expr, self.var) {
1417 walk_expr(self, expr);
1421 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1422 NestedVisitorMap::None
1426 struct LocalUsedVisitor<'a, 'tcx: 'a> {
1427 cx: &'a LateContext<'a, 'tcx>,
1432 impl<'a, 'tcx: 'a> Visitor<'tcx> for LocalUsedVisitor<'a, 'tcx> {
1433 fn visit_expr(&mut self, expr: &'tcx Expr) {
1434 if same_var(self.cx, expr, self.local) {
1437 walk_expr(self, expr);
1441 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1442 NestedVisitorMap::None
1446 struct VarVisitor<'a, 'tcx: 'a> {
1447 /// context reference
1448 cx: &'a LateContext<'a, 'tcx>,
1449 /// var name to look for as index
1451 /// indexed variables, the extend is `None` for global
1452 indexed: HashMap<Name, Option<region::Scope>>,
1453 /// Any names that are used outside an index operation.
1454 /// Used to detect things like `&mut vec` used together with `vec[i]`
1455 referenced: HashSet<Name>,
1456 /// has the loop variable been used in expressions other than the index of
1461 impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
1462 fn visit_expr(&mut self, expr: &'tcx Expr) {
1465 let ExprIndex(ref seqexpr, ref idx) = expr.node,
1466 // the indexed container is referenced by a name
1467 let ExprPath(ref seqpath) = seqexpr.node,
1468 let QPath::Resolved(None, ref seqvar) = *seqpath,
1469 seqvar.segments.len() == 1,
1471 let index_used = same_var(self.cx, idx, self.var) || {
1472 let mut used_visitor = LocalUsedVisitor {
1477 walk_expr(&mut used_visitor, idx);
1482 let def = self.cx.tables.qpath_def(seqpath, seqexpr.hir_id);
1484 Def::Local(node_id) | Def::Upvar(node_id, ..) => {
1485 let hir_id = self.cx.tcx.hir.node_to_hir_id(node_id);
1487 let parent_id = self.cx.tcx.hir.get_parent(expr.id);
1488 let parent_def_id = self.cx.tcx.hir.local_def_id(parent_id);
1489 let extent = self.cx.tcx.region_scope_tree(parent_def_id).var_scope(hir_id.local_id);
1490 self.indexed.insert(seqvar.segments[0].name, Some(extent));
1491 return; // no need to walk further *on the variable*
1493 Def::Static(..) | Def::Const(..) => {
1494 self.indexed.insert(seqvar.segments[0].name, None);
1495 return; // no need to walk further *on the variable*
1503 // directly using a variable
1504 let ExprPath(ref qpath) = expr.node,
1505 let QPath::Resolved(None, ref path) = *qpath,
1506 path.segments.len() == 1,
1507 let Def::Local(local_id) = self.cx.tables.qpath_def(qpath, expr.hir_id),
1509 if local_id == self.var {
1510 // we are not indexing anything, record that
1511 self.nonindex = true;
1513 // not the correct variable, but still a variable
1514 self.referenced.insert(path.segments[0].name);
1518 walk_expr(self, expr);
1520 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1521 NestedVisitorMap::None
1525 fn is_iterator_used_after_while_let<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, iter_expr: &'tcx Expr) -> bool {
1526 let def_id = match var_def_id(cx, iter_expr) {
1528 None => return false,
1530 let mut visitor = VarUsedAfterLoopVisitor {
1533 iter_expr_id: iter_expr.id,
1534 past_while_let: false,
1535 var_used_after_while_let: false,
1537 if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
1538 walk_block(&mut visitor, enclosing_block);
1540 visitor.var_used_after_while_let
1543 struct VarUsedAfterLoopVisitor<'a, 'tcx: 'a> {
1544 cx: &'a LateContext<'a, 'tcx>,
1546 iter_expr_id: NodeId,
1547 past_while_let: bool,
1548 var_used_after_while_let: bool,
1551 impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
1552 fn visit_expr(&mut self, expr: &'tcx Expr) {
1553 if self.past_while_let {
1554 if Some(self.def_id) == var_def_id(self.cx, expr) {
1555 self.var_used_after_while_let = true;
1557 } else if self.iter_expr_id == expr.id {
1558 self.past_while_let = true;
1560 walk_expr(self, expr);
1562 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1563 NestedVisitorMap::None
1568 /// Return true if the type of expr is one that provides `IntoIterator` impls
1569 /// for `&T` and `&mut T`, such as `Vec`.
1570 #[cfg_attr(rustfmt, rustfmt_skip)]
1571 fn is_ref_iterable_type(cx: &LateContext, e: &Expr) -> bool {
1572 // no walk_ptrs_ty: calling iter() on a reference can make sense because it
1573 // will allow further borrows afterwards
1574 let ty = cx.tables.expr_ty(e);
1575 is_iterable_array(ty) ||
1576 match_type(cx, ty, &paths::VEC) ||
1577 match_type(cx, ty, &paths::LINKED_LIST) ||
1578 match_type(cx, ty, &paths::HASHMAP) ||
1579 match_type(cx, ty, &paths::HASHSET) ||
1580 match_type(cx, ty, &paths::VEC_DEQUE) ||
1581 match_type(cx, ty, &paths::BINARY_HEAP) ||
1582 match_type(cx, ty, &paths::BTREEMAP) ||
1583 match_type(cx, ty, &paths::BTREESET)
1586 fn is_iterable_array(ty: Ty) -> bool {
1587 // IntoIterator is currently only implemented for array sizes <= 32 in rustc
1589 ty::TyArray(_, n) => (0...32).contains(const_to_u64(n)),
1594 /// If a block begins with a statement (possibly a `let` binding) and has an
1595 /// expression, return it.
1596 fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
1597 if block.stmts.is_empty() {
1600 if let StmtDecl(ref decl, _) = block.stmts[0].node {
1601 if let DeclLocal(ref local) = decl.node {
1602 if let Some(ref expr) = local.init {
1615 /// If a block begins with an expression (with or without semicolon), return it.
1616 fn extract_first_expr(block: &Block) -> Option<&Expr> {
1618 Some(ref expr) if block.stmts.is_empty() => Some(expr),
1619 None if !block.stmts.is_empty() => {
1620 match block.stmts[0].node {
1621 StmtExpr(ref expr, _) |
1622 StmtSemi(ref expr, _) => Some(expr),
1623 StmtDecl(..) => None,
1630 /// Return true if expr contains a single break expr without destination label
1632 /// passed expression. The expression may be within a block.
1633 fn is_simple_break_expr(expr: &Expr) -> bool {
1635 ExprBreak(dest, ref passed_expr) if dest.ident.is_none() && passed_expr.is_none() => true,
1636 ExprBlock(ref b) => {
1637 match extract_first_expr(b) {
1638 Some(subexpr) => is_simple_break_expr(subexpr),
1646 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
1647 // incremented exactly once in the loop body, and initialized to zero
1648 // at the start of the loop.
1649 #[derive(PartialEq)]
1651 Initial, // Not examined yet
1652 IncrOnce, // Incremented exactly once, may be a loop counter
1653 Declared, // Declared but not (yet) initialized to zero
1658 /// Scan a for loop for variables that are incremented exactly once.
1659 struct IncrementVisitor<'a, 'tcx: 'a> {
1660 cx: &'a LateContext<'a, 'tcx>, // context reference
1661 states: HashMap<NodeId, VarState>, // incremented variables
1662 depth: u32, // depth of conditional expressions
1666 impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
1667 fn visit_expr(&mut self, expr: &'tcx Expr) {
1672 // If node is a variable
1673 if let Some(def_id) = var_def_id(self.cx, expr) {
1674 if let Some(parent) = get_parent_expr(self.cx, expr) {
1675 let state = self.states.entry(def_id).or_insert(VarState::Initial);
1678 ExprAssignOp(op, ref lhs, ref rhs) => {
1679 if lhs.id == expr.id {
1680 if op.node == BiAdd && is_integer_literal(rhs, 1) {
1681 *state = match *state {
1682 VarState::Initial if self.depth == 0 => VarState::IncrOnce,
1683 _ => VarState::DontWarn,
1686 // Assigned some other value
1687 *state = VarState::DontWarn;
1691 ExprAssign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
1692 ExprAddrOf(mutability, _) if mutability == MutMutable => *state = VarState::DontWarn,
1696 } else if is_loop(expr) {
1697 self.states.clear();
1700 } else if is_conditional(expr) {
1702 walk_expr(self, expr);
1706 walk_expr(self, expr);
1708 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1709 NestedVisitorMap::None
1713 /// Check whether a variable is initialized to zero at the start of a loop.
1714 struct InitializeVisitor<'a, 'tcx: 'a> {
1715 cx: &'a LateContext<'a, 'tcx>, // context reference
1716 end_expr: &'tcx Expr, // the for loop. Stop scanning here.
1720 depth: u32, // depth of conditional expressions
1724 impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
1725 fn visit_decl(&mut self, decl: &'tcx Decl) {
1726 // Look for declarations of the variable
1727 if let DeclLocal(ref local) = decl.node {
1728 if local.pat.id == self.var_id {
1729 if let PatKind::Binding(_, _, ref ident, _) = local.pat.node {
1730 self.name = Some(ident.node);
1732 self.state = if let Some(ref init) = local.init {
1733 if is_integer_literal(init, 0) {
1744 walk_decl(self, decl);
1747 fn visit_expr(&mut self, expr: &'tcx Expr) {
1748 if self.state == VarState::DontWarn {
1751 if expr == self.end_expr {
1752 self.past_loop = true;
1755 // No need to visit expressions before the variable is
1757 if self.state == VarState::IncrOnce {
1761 // If node is the desired variable, see how it's used
1762 if var_def_id(self.cx, expr) == Some(self.var_id) {
1763 if let Some(parent) = get_parent_expr(self.cx, expr) {
1765 ExprAssignOp(_, ref lhs, _) if lhs.id == expr.id => {
1766 self.state = VarState::DontWarn;
1768 ExprAssign(ref lhs, ref rhs) if lhs.id == expr.id => {
1769 self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
1775 ExprAddrOf(mutability, _) if mutability == MutMutable => self.state = VarState::DontWarn,
1781 self.state = VarState::DontWarn;
1784 } else if !self.past_loop && is_loop(expr) {
1785 self.state = VarState::DontWarn;
1787 } else if is_conditional(expr) {
1789 walk_expr(self, expr);
1793 walk_expr(self, expr);
1795 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1796 NestedVisitorMap::None
1800 fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
1801 if let ExprPath(ref qpath) = expr.node {
1802 let path_res = cx.tables.qpath_def(qpath, expr.hir_id);
1803 if let Def::Local(node_id) = path_res {
1804 return Some(node_id);
1810 fn is_loop(expr: &Expr) -> bool {
1812 ExprLoop(..) | ExprWhile(..) => true,
1817 fn is_conditional(expr: &Expr) -> bool {
1819 ExprIf(..) | ExprMatch(..) => true,
1824 fn is_nested(cx: &LateContext, match_expr: &Expr, iter_expr: &Expr) -> bool {
1826 let Some(loop_block) = get_enclosing_block(cx, match_expr.id),
1827 let Some(map::Node::NodeExpr(loop_expr)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(loop_block.id)),
1829 return is_loop_nested(cx, loop_expr, iter_expr)
1834 fn is_loop_nested(cx: &LateContext, loop_expr: &Expr, iter_expr: &Expr) -> bool {
1835 let mut id = loop_expr.id;
1836 let iter_name = if let Some(name) = path_name(iter_expr) {
1842 let parent = cx.tcx.hir.get_parent_node(id);
1846 match cx.tcx.hir.find(parent) {
1847 Some(NodeExpr(expr)) => {
1849 ExprLoop(..) | ExprWhile(..) => {
1855 Some(NodeBlock(block)) => {
1856 let mut block_visitor = LoopNestVisitor {
1858 iterator: iter_name,
1861 walk_block(&mut block_visitor, block);
1862 if block_visitor.nesting == RuledOut {
1866 Some(NodeStmt(_)) => (),
1875 #[derive(PartialEq, Eq)]
1877 Unknown, // no nesting detected yet
1878 RuledOut, // the iterator is initialized or assigned within scope
1879 LookFurther, // no nesting detected, no further walk required
1882 use self::Nesting::{LookFurther, RuledOut, Unknown};
1884 struct LoopNestVisitor {
1890 impl<'tcx> Visitor<'tcx> for LoopNestVisitor {
1891 fn visit_stmt(&mut self, stmt: &'tcx Stmt) {
1892 if stmt.node.id() == self.id {
1893 self.nesting = LookFurther;
1894 } else if self.nesting == Unknown {
1895 walk_stmt(self, stmt);
1899 fn visit_expr(&mut self, expr: &'tcx Expr) {
1900 if self.nesting != Unknown {
1903 if expr.id == self.id {
1904 self.nesting = LookFurther;
1908 ExprAssign(ref path, _) |
1909 ExprAssignOp(_, ref path, _) => {
1910 if match_var(path, self.iterator) {
1911 self.nesting = RuledOut;
1914 _ => walk_expr(self, expr),
1918 fn visit_pat(&mut self, pat: &'tcx Pat) {
1919 if self.nesting != Unknown {
1922 if let PatKind::Binding(_, _, span_name, _) = pat.node {
1923 if self.iterator == span_name.node {
1924 self.nesting = RuledOut;
1931 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1932 NestedVisitorMap::None
1936 fn path_name(e: &Expr) -> Option<Name> {
1937 if let ExprPath(QPath::Resolved(_, ref path)) = e.node {
1938 let segments = &path.segments;
1939 if segments.len() == 1 {
1940 return Some(segments[0].name);