1 use itertools::Itertools;
4 use rustc::hir::def::Def;
5 use rustc::hir::def_id;
6 use rustc::hir::intravisit::{walk_block, walk_decl, walk_expr, walk_pat, walk_stmt, NestedVisitorMap, Visitor};
7 use rustc::hir::map::Node::{NodeBlock, NodeExpr, NodeStmt};
9 use rustc::middle::const_val::ConstVal;
10 use rustc::middle::region;
11 // use rustc::middle::region::CodeExtent;
12 use rustc::middle::expr_use_visitor::*;
13 use rustc::middle::mem_categorization::Categorization;
14 use rustc::middle::mem_categorization::cmt;
15 use rustc::ty::{self, Ty};
16 use rustc::ty::subst::{Subst, Substs};
17 use rustc_const_eval::ConstContext;
18 use std::collections::{HashMap, HashSet};
19 use std::iter::{once, Iterator};
21 use syntax::codemap::Span;
23 use utils::const_to_u64;
25 use utils::{get_enclosing_block, get_parent_expr, higher, in_external_macro, is_integer_literal, is_refutable,
26 last_path_segment, match_trait_method, match_type, match_var, multispan_sugg, snippet, snippet_opt,
27 span_help_and_lint, span_lint, span_lint_and_sugg, span_lint_and_then};
30 /// **What it does:** Checks for for-loops that manually copy items between
31 /// slices that could be optimized by having a memcpy.
33 /// **Why is this bad?** It is not as fast as a memcpy.
35 /// **Known problems:** None.
39 /// for i in 0..src.len() {
40 /// dst[i + 64] = src[i];
46 "manually copying items between slices"
49 /// **What it does:** Checks for looping over the range of `0..len` of some
50 /// collection just to get the values by index.
52 /// **Why is this bad?** Just iterating the collection itself makes the intent
53 /// more clear and is probably faster.
55 /// **Known problems:** None.
59 /// for i in 0..vec.len() {
60 /// println!("{}", vec[i]);
64 pub NEEDLESS_RANGE_LOOP,
66 "for-looping over a range of indices where an iterator over items would do"
69 /// **What it does:** Checks for loops on `x.iter()` where `&x` will do, and
70 /// suggests the latter.
72 /// **Why is this bad?** Readability.
74 /// **Known problems:** False negatives. We currently only warn on some known
79 /// // with `y` a `Vec` or slice:
80 /// for x in y.iter() { .. }
83 pub EXPLICIT_ITER_LOOP,
85 "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
88 /// **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and
89 /// suggests the latter.
91 /// **Why is this bad?** Readability.
93 /// **Known problems:** None
97 /// // with `y` a `Vec` or slice:
98 /// for x in y.into_iter() { .. }
101 pub EXPLICIT_INTO_ITER_LOOP,
103 "for-looping over `_.into_iter()` when `_` would do"
106 /// **What it does:** Checks for loops on `x.next()`.
108 /// **Why is this bad?** `next()` returns either `Some(value)` if there was a
109 /// value, or `None` otherwise. The insidious thing is that `Option<_>`
110 /// implements `IntoIterator`, so that possibly one value will be iterated,
111 /// leading to some hard to find bugs. No one will want to write such code
112 /// [except to win an Underhanded Rust
113 /// Contest](https://www.reddit.
114 /// com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
116 /// **Known problems:** None.
120 /// for x in y.next() { .. }
125 "for-looping over `_.next()` which is probably not intended"
128 /// **What it does:** Checks for `for` loops over `Option` values.
130 /// **Why is this bad?** Readability. This is more clearly expressed as an `if
133 /// **Known problems:** None.
137 /// for x in option { .. }
142 /// if let Some(x) = option { .. }
145 pub FOR_LOOP_OVER_OPTION,
147 "for-looping over an `Option`, which is more clearly expressed as an `if let`"
150 /// **What it does:** Checks for `for` loops over `Result` values.
152 /// **Why is this bad?** Readability. This is more clearly expressed as an `if
155 /// **Known problems:** None.
159 /// for x in result { .. }
164 /// if let Ok(x) = result { .. }
167 pub FOR_LOOP_OVER_RESULT,
169 "for-looping over a `Result`, which is more clearly expressed as an `if let`"
172 /// **What it does:** Detects `loop + match` combinations that are easier
173 /// written as a `while let` loop.
175 /// **Why is this bad?** The `while let` loop is usually shorter and more
178 /// **Known problems:** Sometimes the wrong binding is displayed (#383).
183 /// let x = match y {
187 /// // .. do something with x
189 /// // is easier written as
190 /// while let Some(x) = y {
191 /// // .. do something with x
197 "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
200 /// **What it does:** Checks for using `collect()` on an iterator without using
203 /// **Why is this bad?** It is more idiomatic to use a `for` loop over the
204 /// iterator instead.
206 /// **Known problems:** None.
210 /// vec.iter().map(|x| /* some operation returning () */).collect::<Vec<_>>();
215 "`collect()`ing an iterator without using the result; this is usually better \
216 written as a for loop"
219 /// **What it does:** Checks for loops over ranges `x..y` where both `x` and `y`
220 /// are constant and `x` is greater or equal to `y`, unless the range is
221 /// reversed or has a negative `.step_by(_)`.
223 /// **Why is it bad?** Such loops will either be skipped or loop until
224 /// wrap-around (in debug code, this may `panic!()`). Both options are probably
227 /// **Known problems:** The lint cannot catch loops over dynamically defined
228 /// ranges. Doing this would require simulating all possible inputs and code
229 /// paths through the program, which would be complex and error-prone.
233 /// for x in 5..10-5 { .. } // oops, stray `-`
236 pub REVERSE_RANGE_LOOP,
238 "iteration over an empty range, such as `10..0` or `5..5`"
241 /// **What it does:** Checks `for` loops over slices with an explicit counter
242 /// and suggests the use of `.enumerate()`.
244 /// **Why is it bad?** Not only is the version using `.enumerate()` more
245 /// readable, the compiler is able to remove bounds checks which can lead to
246 /// faster code in some instances.
248 /// **Known problems:** None.
252 /// for i in 0..v.len() { foo(v[i]);
253 /// for i in 0..v.len() { bar(i, v[i]); }
256 pub EXPLICIT_COUNTER_LOOP,
258 "for-looping with an explicit counter when `_.enumerate()` would do"
261 /// **What it does:** Checks for empty `loop` expressions.
263 /// **Why is this bad?** Those busy loops burn CPU cycles without doing
264 /// anything. Think of the environment and either block on something or at least
265 /// make the thread sleep for some microseconds.
267 /// **Known problems:** None.
276 "empty `loop {}`, which should block or sleep"
279 /// **What it does:** Checks for `while let` expressions on iterators.
281 /// **Why is this bad?** Readability. A simple `for` loop is shorter and conveys
282 /// the intent better.
284 /// **Known problems:** None.
288 /// while let Some(val) = iter() { .. }
291 pub WHILE_LET_ON_ITERATOR,
293 "using a while-let loop instead of a for loop on an iterator"
296 /// **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and
297 /// ignoring either the keys or values.
299 /// **Why is this bad?** Readability. There are `keys` and `values` methods that
300 /// can be used to express that don't need the values or keys.
302 /// **Known problems:** None.
306 /// for (k, _) in &map { .. }
309 /// could be replaced by
312 /// for k in map.keys() { .. }
317 "looping on a map using `iter` when `keys` or `values` would do"
320 /// **What it does:** Checks for loops that will always `break`, `return` or
321 /// `continue` an outer loop.
323 /// **Why is this bad?** This loop never loops, all it does is obfuscating the
326 /// **Known problems:** None
330 /// loop { ..; break; }
335 "any loop that will always `break` or `return`"
338 /// TODO: add documentation
343 "for loop over a range where one of the bounds is a mutable variable"
346 /// **What it does:** Checks whether variables used within while loop condition
347 /// can be (and are) mutated in the body.
349 /// **Why is this bad?** If the condition is unchanged, entering the body of the loop
350 /// will lead to an infinite loop.
352 /// **Known problems:** None
358 /// println!("let me loop forever!");
362 pub WHILE_IMMUTABLE_CONDITION,
364 "variables used within while expression are not mutated in the body"
367 #[derive(Copy, Clone)]
370 impl LintPass for Pass {
371 fn get_lints(&self) -> LintArray {
376 EXPLICIT_INTO_ITER_LOOP,
378 FOR_LOOP_OVER_RESULT,
379 FOR_LOOP_OVER_OPTION,
383 EXPLICIT_COUNTER_LOOP,
385 WHILE_LET_ON_ITERATOR,
389 WHILE_IMMUTABLE_CONDITION,
394 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
395 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
396 if let Some((pat, arg, body)) = higher::for_loop(expr) {
397 check_for_loop(cx, pat, arg, body, expr);
400 // check for never_loop
402 ExprWhile(_, ref block, _) | ExprLoop(ref block, _, _) => {
403 match never_loop_block(block, &expr.id) {
404 NeverLoopResult::AlwaysBreak =>
405 span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops"),
406 NeverLoopResult::MayContinueMainLoop | NeverLoopResult::Otherwise => (),
412 // check for `loop { if let {} else break }` that could be `while let`
413 // (also matches an explicit "match" instead of "if let")
414 // (even if the "match" or "if let" is used for declaration)
415 if let ExprLoop(ref block, _, LoopSource::Loop) = expr.node {
416 // also check for empty `loop {}` statements
417 if block.stmts.is_empty() && block.expr.is_none() {
422 "empty `loop {}` detected. You may want to either use `panic!()` or add \
423 `std::thread::sleep(..);` to the loop body.",
427 // extract the expression from the first statement (if any) in a block
428 let inner_stmt_expr = extract_expr_from_first_stmt(block);
429 // or extract the first expression (if any) from the block
430 if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
431 if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node {
432 // ensure "if let" compatible match structure
434 MatchSource::Normal | MatchSource::IfLetDesugar { .. } => {
435 if arms.len() == 2 && arms[0].pats.len() == 1 && arms[0].guard.is_none()
436 && arms[1].pats.len() == 1 && arms[1].guard.is_none()
437 && is_simple_break_expr(&arms[1].body)
439 if in_external_macro(cx, expr.span) {
443 // NOTE: we used to make build a body here instead of using
444 // ellipsis, this was removed because:
445 // 1) it was ugly with big bodies;
446 // 2) it was not indented properly;
447 // 3) it wasn’t very smart (see #675).
452 "this loop could be written as a `while let` loop",
455 "while let {} = {} {{ .. }}",
456 snippet(cx, arms[0].pats[0].span, ".."),
457 snippet(cx, matchexpr.span, "..")
467 if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
468 let pat = &arms[0].pats[0].node;
470 &PatKind::TupleStruct(ref qpath, ref pat_args, _),
471 &ExprMethodCall(ref method_path, _, ref method_args),
472 ) = (pat, &match_expr.node)
474 let iter_expr = &method_args[0];
475 let lhs_constructor = last_path_segment(qpath);
476 if method_path.name == "next" && match_trait_method(cx, match_expr, &paths::ITERATOR)
477 && lhs_constructor.name == "Some" && !is_refutable(cx, &pat_args[0])
478 && !is_iterator_used_after_while_let(cx, iter_expr)
479 && !is_nested(cx, expr, &method_args[0])
481 let iterator = snippet(cx, method_args[0].span, "_");
482 let loop_var = snippet(cx, pat_args[0].span, "_");
485 WHILE_LET_ON_ITERATOR,
487 "this loop could be written as a `for` loop",
489 format!("for {} in {} {{ .. }}", loop_var, iterator),
495 // check for while loops which conditions never change
496 if let ExprWhile(ref cond, ref block, _) = expr.node {
497 check_infinite_loop(cx, cond, block, expr);
501 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
502 if let StmtSemi(ref expr, _) = stmt.node {
503 if let ExprMethodCall(ref method, _, ref args) = expr.node {
504 if args.len() == 1 && method.name == "collect" && match_trait_method(cx, expr, &paths::ITERATOR) {
509 "you are collect()ing an iterator and throwing away the result. \
510 Consider using an explicit for loop to exhaust the iterator",
518 enum NeverLoopResult {
519 // A break/return always get triggered but not necessarily for the main loop.
521 // A continue may occur for the main loop.
526 fn absorb_break(arg: &NeverLoopResult) -> NeverLoopResult {
528 NeverLoopResult::AlwaysBreak |
529 NeverLoopResult::Otherwise => NeverLoopResult::Otherwise,
530 NeverLoopResult::MayContinueMainLoop => NeverLoopResult::MayContinueMainLoop,
534 // Combine two results for parts that are called in order.
535 fn combine_seq(first: NeverLoopResult, second: NeverLoopResult) -> NeverLoopResult {
537 NeverLoopResult::AlwaysBreak | NeverLoopResult::MayContinueMainLoop => first,
538 NeverLoopResult::Otherwise => second,
542 // Combine two results where both parts are called but not necessarily in order.
543 fn combine_both(left: NeverLoopResult, right: NeverLoopResult) -> NeverLoopResult {
544 match (left, right) {
545 (NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) =>
546 NeverLoopResult::MayContinueMainLoop,
547 (NeverLoopResult::AlwaysBreak, _) | (_, NeverLoopResult::AlwaysBreak) =>
548 NeverLoopResult::AlwaysBreak,
549 (NeverLoopResult::Otherwise, NeverLoopResult::Otherwise) =>
550 NeverLoopResult::Otherwise,
554 // Combine two results where only one of the part may have been executed.
555 fn combine_branches(b1: NeverLoopResult, b2: NeverLoopResult) -> NeverLoopResult {
557 (NeverLoopResult::AlwaysBreak, NeverLoopResult::AlwaysBreak) =>
558 NeverLoopResult::AlwaysBreak,
559 (NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) =>
560 NeverLoopResult::MayContinueMainLoop,
561 (NeverLoopResult::Otherwise, _) | (_, NeverLoopResult::Otherwise) =>
562 NeverLoopResult::Otherwise,
566 fn never_loop_block(block: &Block, main_loop_id: &NodeId) -> NeverLoopResult {
567 let stmts = block.stmts.iter().map(stmt_to_expr);
568 let expr = once(block.expr.as_ref().map(|p| &**p));
569 let mut iter = stmts.chain(expr).filter_map(|e| e);
570 never_loop_expr_seq(&mut iter, main_loop_id)
573 fn stmt_to_expr(stmt: &Stmt) -> Option<&Expr> {
575 StmtSemi(ref e, ..) | StmtExpr(ref e, ..) => Some(e),
576 StmtDecl(ref d, ..) => decl_to_expr(d),
580 fn decl_to_expr(decl: &Decl) -> Option<&Expr> {
582 DeclLocal(ref local) => local.init.as_ref().map(|p| &**p),
587 fn never_loop_expr(expr: &Expr, main_loop_id: &NodeId) -> NeverLoopResult {
590 ExprUnary(_, ref e) |
593 ExprField(ref e, _) |
594 ExprTupField(ref e, _) |
595 ExprAddrOf(_, ref e) |
596 ExprStruct(_, _, Some(ref e)) |
597 ExprRepeat(ref e, _) => never_loop_expr(e, main_loop_id),
598 ExprArray(ref es) | ExprMethodCall(_, _, ref es) | ExprTup(ref es) => {
599 never_loop_expr_all(&mut es.iter(), main_loop_id)
601 ExprCall(ref e, ref es) => never_loop_expr_all(&mut once(&**e).chain(es.iter()), main_loop_id),
602 ExprBinary(_, ref e1, ref e2) |
603 ExprAssign(ref e1, ref e2) |
604 ExprAssignOp(_, ref e1, ref e2) |
605 ExprIndex(ref e1, ref e2) => never_loop_expr_all(&mut [&**e1, &**e2].iter().cloned(), main_loop_id),
606 ExprIf(ref e, ref e2, ref e3) => {
607 let e1 = never_loop_expr(e, main_loop_id);
608 let e2 = never_loop_expr(e2, main_loop_id);
609 let e3 = e3.as_ref().map_or(NeverLoopResult::Otherwise, |e| never_loop_expr(e, main_loop_id));
610 combine_seq(e1, combine_branches(e2, e3))
612 ExprLoop(ref b, _, _) => {
613 // Break can come from the inner loop so remove them.
614 absorb_break(&never_loop_block(b, main_loop_id))
616 ExprWhile(ref e, ref b, _) => {
617 let e = never_loop_expr(e, main_loop_id);
618 let result = never_loop_block(b, main_loop_id);
619 // Break can come from the inner loop so remove them.
620 combine_seq(e, absorb_break(&result))
622 ExprMatch(ref e, ref arms, _) => {
623 let e = never_loop_expr(e, main_loop_id);
627 let arms = never_loop_expr_branch(&mut arms.iter().map(|a| &*a.body), main_loop_id);
631 ExprBlock(ref b) => never_loop_block(b, main_loop_id),
635 .expect("target id can only be missing in the presence of compilation errors");
636 if id == *main_loop_id {
637 NeverLoopResult::MayContinueMainLoop
639 NeverLoopResult::AlwaysBreak
643 NeverLoopResult::AlwaysBreak
646 if let Some(ref e) = *e {
647 combine_seq(never_loop_expr(e, main_loop_id), NeverLoopResult::AlwaysBreak)
649 NeverLoopResult::AlwaysBreak
652 ExprStruct(_, _, None) |
654 ExprClosure(_, _, _, _, _) |
655 ExprInlineAsm(_, _, _) |
657 ExprLit(_) => NeverLoopResult::Otherwise,
661 fn never_loop_expr_seq<'a, T: Iterator<Item=&'a Expr>>(es: &mut T, main_loop_id: &NodeId) -> NeverLoopResult {
662 es.map(|e| never_loop_expr(e, main_loop_id))
663 .fold(NeverLoopResult::Otherwise, combine_seq)
666 fn never_loop_expr_all<'a, T: Iterator<Item=&'a Expr>>(es: &mut T, main_loop_id: &NodeId) -> NeverLoopResult {
667 es.map(|e| never_loop_expr(e, main_loop_id))
668 .fold(NeverLoopResult::Otherwise, combine_both)
671 fn never_loop_expr_branch<'a, T: Iterator<Item=&'a Expr>>(e: &mut T, main_loop_id: &NodeId) -> NeverLoopResult {
672 e.map(|e| never_loop_expr(e, main_loop_id))
673 .fold(NeverLoopResult::AlwaysBreak, combine_branches)
676 fn check_for_loop<'a, 'tcx>(
677 cx: &LateContext<'a, 'tcx>,
683 check_for_loop_range(cx, pat, arg, body, expr);
684 check_for_loop_reverse_range(cx, arg, expr);
685 check_for_loop_arg(cx, pat, arg, expr);
686 check_for_loop_explicit_counter(cx, arg, body, expr);
687 check_for_loop_over_map_kv(cx, pat, arg, body, expr);
688 check_for_mut_range_bound(cx, arg, body);
689 detect_manual_memcpy(cx, pat, arg, body, expr);
692 fn same_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr, var: ast::NodeId) -> bool {
694 if let ExprPath(ref qpath) = expr.node;
695 if let QPath::Resolved(None, ref path) = *qpath;
696 if path.segments.len() == 1;
697 if let Def::Local(local_id) = cx.tables.qpath_def(qpath, expr.hir_id);
714 fn negative(s: String) -> Self {
721 fn positive(s: String) -> Self {
729 struct FixedOffsetVar {
734 fn is_slice_like<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty) -> bool {
735 let is_slice = match ty.sty {
736 ty::TyRef(_, ref subty) => is_slice_like(cx, subty.ty),
737 ty::TySlice(..) | ty::TyArray(..) => true,
741 is_slice || match_type(cx, ty, &paths::VEC) || match_type(cx, ty, &paths::VEC_DEQUE)
744 fn get_fixed_offset_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr, var: ast::NodeId) -> Option<FixedOffsetVar> {
745 fn extract_offset<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &Expr, var: ast::NodeId) -> Option<String> {
747 ExprLit(ref l) => match l.node {
748 ast::LitKind::Int(x, _ty) => Some(x.to_string()),
751 ExprPath(..) if !same_var(cx, e, var) => Some(snippet_opt(cx, e.span).unwrap_or_else(|| "??".into())),
756 if let ExprIndex(ref seqexpr, ref idx) = expr.node {
757 let ty = cx.tables.expr_ty(seqexpr);
758 if !is_slice_like(cx, ty) {
762 let offset = match idx.node {
763 ExprBinary(op, ref lhs, ref rhs) => match op.node {
765 let offset_opt = if same_var(cx, lhs, var) {
766 extract_offset(cx, rhs, var)
767 } else if same_var(cx, rhs, var) {
768 extract_offset(cx, lhs, var)
773 offset_opt.map(Offset::positive)
775 BinOp_::BiSub if same_var(cx, lhs, var) => extract_offset(cx, rhs, var).map(Offset::negative),
778 ExprPath(..) => if same_var(cx, idx, var) {
779 Some(Offset::positive("0".into()))
788 var_name: snippet_opt(cx, seqexpr.span).unwrap_or_else(|| "???".into()),
797 fn fetch_cloned_fixed_offset_var<'a, 'tcx>(
798 cx: &LateContext<'a, 'tcx>,
801 ) -> Option<FixedOffsetVar> {
803 if let ExprMethodCall(ref method, _, ref args) = expr.node;
804 if method.name == "clone";
806 if let Some(arg) = args.get(0);
808 return get_fixed_offset_var(cx, arg, var);
812 get_fixed_offset_var(cx, expr, var)
815 fn get_indexed_assignments<'a, 'tcx>(
816 cx: &LateContext<'a, 'tcx>,
819 ) -> Vec<(FixedOffsetVar, FixedOffsetVar)> {
820 fn get_assignment<'a, 'tcx>(
821 cx: &LateContext<'a, 'tcx>,
824 ) -> Option<(FixedOffsetVar, FixedOffsetVar)> {
825 if let Expr_::ExprAssign(ref lhs, ref rhs) = e.node {
826 match (get_fixed_offset_var(cx, lhs, var), fetch_cloned_fixed_offset_var(cx, rhs, var)) {
827 (Some(offset_left), Some(offset_right)) => {
828 // Source and destination must be different
829 if offset_left.var_name == offset_right.var_name {
832 Some((offset_left, offset_right))
842 if let Expr_::ExprBlock(ref b) = body.node {
851 .map(|stmt| match stmt.node {
852 Stmt_::StmtDecl(..) => None,
853 Stmt_::StmtExpr(ref e, _node_id) | Stmt_::StmtSemi(ref e, _node_id) => Some(get_assignment(cx, e, var)),
858 .map(|e| Some(get_assignment(cx, &*e, var))),
861 .collect::<Option<Vec<_>>>()
862 .unwrap_or_else(|| vec![])
864 get_assignment(cx, body, var).into_iter().collect()
868 /// Check for for loops that sequentially copy items from one slice-like
869 /// object to another.
870 fn detect_manual_memcpy<'a, 'tcx>(
871 cx: &LateContext<'a, 'tcx>,
877 if let Some(higher::Range {
881 }) = higher::range(arg)
883 // the var must be a single name
884 if let PatKind::Binding(_, canonical_id, _, _) = pat.node {
885 let print_sum = |arg1: &Offset, arg2: &Offset| -> String {
886 match (&arg1.value[..], arg1.negate, &arg2.value[..], arg2.negate) {
887 ("0", _, "0", _) => "".into(),
888 ("0", _, x, false) | (x, false, "0", false) => x.into(),
889 ("0", _, x, true) | (x, false, "0", true) => format!("-{}", x),
890 (x, false, y, false) => format!("({} + {})", x, y),
891 (x, false, y, true) => format!("({} - {})", x, y),
892 (x, true, y, false) => format!("({} - {})", y, x),
893 (x, true, y, true) => format!("-({} + {})", x, y),
897 let print_limit = |end: &Option<&Expr>, offset: Offset, var_name: &str| if let Some(end) = *end {
899 if let ExprMethodCall(ref method, _, ref len_args) = end.node;
900 if method.name == "len";
901 if len_args.len() == 1;
902 if let Some(arg) = len_args.get(0);
903 if snippet(cx, arg.span, "??") == var_name;
905 return if offset.negate {
906 format!("({} - {})", snippet(cx, end.span, "<src>.len()"), offset.value)
913 let end_str = match limits {
914 ast::RangeLimits::Closed => {
915 let end = sugg::Sugg::hir(cx, end, "<count>");
916 format!("{}", end + sugg::ONE)
918 ast::RangeLimits::HalfOpen => format!("{}", snippet(cx, end.span, "..")),
921 print_sum(&Offset::positive(end_str), &offset)
926 // The only statements in the for loops can be indexed assignments from
927 // indexed retrievals.
928 let manual_copies = get_indexed_assignments(cx, body, canonical_id);
930 let big_sugg = manual_copies
932 .map(|(dst_var, src_var)| {
933 let start_str = Offset::positive(snippet_opt(cx, start.span).unwrap_or_else(|| "".into()));
934 let dst_offset = print_sum(&start_str, &dst_var.offset);
935 let dst_limit = print_limit(end, dst_var.offset, &dst_var.var_name);
936 let src_offset = print_sum(&start_str, &src_var.offset);
937 let src_limit = print_limit(end, src_var.offset, &src_var.var_name);
938 let dst = if dst_offset == "" && dst_limit == "" {
941 format!("{}[{}..{}]", dst_var.var_name, dst_offset, dst_limit)
944 format!("{}.clone_from_slice(&{}[{}..{}])", dst, src_var.var_name, src_offset, src_limit)
948 if !big_sugg.is_empty() {
953 "it looks like you're manually copying between slices",
954 "try replacing the loop by",
962 /// Check for looping over a range and then indexing a sequence with it.
963 /// The iteratee must be a range literal.
964 fn check_for_loop_range<'a, 'tcx>(
965 cx: &LateContext<'a, 'tcx>,
971 if let Some(higher::Range {
975 }) = higher::range(arg)
977 // the var must be a single name
978 if let PatKind::Binding(_, canonical_id, ref ident, _) = pat.node {
979 let mut visitor = VarVisitor {
982 indexed_mut: HashSet::new(),
983 indexed_indirectly: HashMap::new(),
984 indexed_directly: HashMap::new(),
985 referenced: HashSet::new(),
987 prefer_mutable: false,
989 walk_expr(&mut visitor, body);
991 // linting condition: we only indexed one variable, and indexed it directly
992 if visitor.indexed_indirectly.is_empty() && visitor.indexed_directly.len() == 1 {
993 let (indexed, indexed_extent) = visitor
997 .expect("already checked that we have exactly 1 element");
999 // ensure that the indexed variable was declared before the loop, see #601
1000 if let Some(indexed_extent) = indexed_extent {
1001 let parent_id = cx.tcx.hir.get_parent(expr.id);
1002 let parent_def_id = cx.tcx.hir.local_def_id(parent_id);
1003 let region_scope_tree = cx.tcx.region_scope_tree(parent_def_id);
1004 let pat_extent = region_scope_tree.var_scope(pat.hir_id.local_id);
1005 if region_scope_tree.is_subscope_of(indexed_extent, pat_extent) {
1010 // don't lint if the container that is indexed into is also used without
1012 if visitor.referenced.contains(&indexed) {
1016 let starts_at_zero = is_integer_literal(start, 0);
1018 let skip = if starts_at_zero {
1021 format!(".skip({})", snippet(cx, start.span, ".."))
1024 let take = if let Some(end) = *end {
1025 if is_len_call(end, &indexed) {
1029 ast::RangeLimits::Closed => {
1030 let end = sugg::Sugg::hir(cx, end, "<count>");
1031 format!(".take({})", end + sugg::ONE)
1033 ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, end.span, "..")),
1040 let (ref_mut, method) = if visitor.indexed_mut.contains(&indexed) {
1041 ("mut ", "iter_mut")
1046 if visitor.nonindex {
1049 NEEDLESS_RANGE_LOOP,
1051 &format!("the loop variable `{}` is used to index `{}`", ident.node, indexed),
1055 "consider using an iterator".to_string(),
1057 (pat.span, format!("({}, <item>)", ident.node)),
1058 (arg.span, format!("{}.{}().enumerate(){}{}", indexed, method, take, skip)),
1064 let repl = if starts_at_zero && take.is_empty() {
1065 format!("&{}{}", ref_mut, indexed)
1067 format!("{}.{}(){}{}", indexed, method, take, skip)
1072 NEEDLESS_RANGE_LOOP,
1074 &format!("the loop variable `{}` is only used to index `{}`.", ident.node, indexed),
1078 "consider using an iterator".to_string(),
1079 vec![(pat.span, "<item>".to_string()), (arg.span, repl)],
1089 fn is_len_call(expr: &Expr, var: &Name) -> bool {
1091 if let ExprMethodCall(ref method, _, ref len_args) = expr.node;
1092 if len_args.len() == 1;
1093 if method.name == "len";
1094 if let ExprPath(QPath::Resolved(_, ref path)) = len_args[0].node;
1095 if path.segments.len() == 1;
1096 if path.segments[0].name == *var;
1105 fn check_for_loop_reverse_range<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arg: &'tcx Expr, expr: &'tcx Expr) {
1106 // if this for loop is iterating over a two-sided range...
1107 if let Some(higher::Range {
1111 }) = higher::range(arg)
1113 // ...and both sides are compile-time constant integers...
1114 let parent_item = cx.tcx.hir.get_parent(arg.id);
1115 let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
1116 let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
1117 let constcx = ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables);
1118 if let Ok(start_idx) = constcx.eval(start) {
1119 if let Ok(end_idx) = constcx.eval(end) {
1120 // ...and the start index is greater than the end index,
1121 // this loop will never run. This is often confusing for developers
1122 // who think that this will iterate from the larger value to the
1124 let (sup, eq) = match (start_idx, end_idx) {
1127 val: ConstVal::Integral(start_idx),
1131 val: ConstVal::Integral(end_idx),
1134 ) => (start_idx > end_idx, start_idx == end_idx),
1135 _ => (false, false),
1139 let start_snippet = snippet(cx, start.span, "_");
1140 let end_snippet = snippet(cx, end.span, "_");
1141 let dots = if limits == ast::RangeLimits::Closed {
1151 "this range is empty so this for loop will never run",
1155 "consider using the following if you are attempting to iterate over this \
1158 "({end}{dots}{start}).rev()",
1161 start = start_snippet
1166 } else if eq && limits != ast::RangeLimits::Closed {
1167 // if they are equal, it's also problematic - this loop
1173 "this range is empty so this for loop will never run",
1181 fn lint_iter_method(cx: &LateContext, args: &[Expr], arg: &Expr, method_name: &str) {
1182 let object = snippet(cx, args[0].span, "_");
1183 let muta = if method_name == "iter_mut" {
1192 "it is more idiomatic to loop over references to containers instead of using explicit \
1194 "to write this more concisely, try",
1195 format!("&{}{}", muta, object),
1199 fn check_for_loop_arg(cx: &LateContext, pat: &Pat, arg: &Expr, expr: &Expr) {
1200 let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
1201 if let ExprMethodCall(ref method, _, ref args) = arg.node {
1202 // just the receiver, no arguments
1203 if args.len() == 1 {
1204 let method_name = &*method.name.as_str();
1205 // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
1206 if method_name == "iter" || method_name == "iter_mut" {
1207 if is_ref_iterable_type(cx, &args[0]) {
1208 lint_iter_method(cx, args, arg, method_name);
1210 } else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
1211 let def_id = cx.tables.type_dependent_defs()[arg.hir_id].def_id();
1212 let substs = cx.tables.node_substs(arg.hir_id);
1213 let method_type = cx.tcx.type_of(def_id).subst(cx.tcx, substs);
1215 let fn_arg_tys = method_type.fn_sig(cx.tcx).inputs();
1216 assert_eq!(fn_arg_tys.skip_binder().len(), 1);
1217 if fn_arg_tys.skip_binder()[0].is_region_ptr() {
1218 match cx.tables.expr_ty(&args[0]).sty {
1219 // If the length is greater than 32 no traits are implemented for array and
1220 // therefore we cannot use `&`.
1221 ty::TypeVariants::TyArray(_, size) if const_to_u64(size) > 32 => (),
1222 _ => lint_iter_method(cx, args, arg, method_name),
1225 let object = snippet(cx, args[0].span, "_");
1228 EXPLICIT_INTO_ITER_LOOP,
1230 "it is more idiomatic to loop over containers instead of using explicit \
1231 iteration methods`",
1232 "to write this more concisely, try",
1236 } else if method_name == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
1241 "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
1242 probably not what you want",
1244 next_loop_linted = true;
1248 if !next_loop_linted {
1249 check_arg_type(cx, pat, arg);
1253 /// Check for `for` loops over `Option`s and `Results`
1254 fn check_arg_type(cx: &LateContext, pat: &Pat, arg: &Expr) {
1255 let ty = cx.tables.expr_ty(arg);
1256 if match_type(cx, ty, &paths::OPTION) {
1259 FOR_LOOP_OVER_OPTION,
1262 "for loop over `{0}`, which is an `Option`. This is more readably written as an \
1263 `if let` statement.",
1264 snippet(cx, arg.span, "_")
1267 "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
1268 snippet(cx, pat.span, "_"),
1269 snippet(cx, arg.span, "_")
1272 } else if match_type(cx, ty, &paths::RESULT) {
1275 FOR_LOOP_OVER_RESULT,
1278 "for loop over `{0}`, which is a `Result`. This is more readably written as an \
1279 `if let` statement.",
1280 snippet(cx, arg.span, "_")
1283 "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
1284 snippet(cx, pat.span, "_"),
1285 snippet(cx, arg.span, "_")
1291 fn check_for_loop_explicit_counter<'a, 'tcx>(
1292 cx: &LateContext<'a, 'tcx>,
1297 // Look for variables that are incremented once per loop iteration.
1298 let mut visitor = IncrementVisitor {
1300 states: HashMap::new(),
1304 walk_expr(&mut visitor, body);
1306 // For each candidate, check the parent block to see if
1307 // it's initialized to zero at the start of the loop.
1308 let map = &cx.tcx.hir;
1309 let parent_scope = map.get_enclosing_scope(expr.id)
1310 .and_then(|id| map.get_enclosing_scope(id));
1311 if let Some(parent_id) = parent_scope {
1312 if let NodeBlock(block) = map.get(parent_id) {
1313 for (id, _) in visitor
1316 .filter(|&(_, v)| *v == VarState::IncrOnce)
1318 let mut visitor2 = InitializeVisitor {
1322 state: VarState::IncrOnce,
1327 walk_block(&mut visitor2, block);
1329 if visitor2.state == VarState::Warn {
1330 if let Some(name) = visitor2.name {
1333 EXPLICIT_COUNTER_LOOP,
1336 "the variable `{0}` is used as a loop counter. Consider using `for ({0}, \
1337 item) in {1}.enumerate()` or similar iterators",
1339 snippet(cx, arg.span, "_")
1349 /// Check for the `FOR_KV_MAP` lint.
1350 fn check_for_loop_over_map_kv<'a, 'tcx>(
1351 cx: &LateContext<'a, 'tcx>,
1357 let pat_span = pat.span;
1359 if let PatKind::Tuple(ref pat, _) = pat.node {
1361 let arg_span = arg.span;
1362 let (new_pat_span, kind, ty, mutbl) = match cx.tables.expr_ty(arg).sty {
1363 ty::TyRef(_, ref tam) => match (&pat[0].node, &pat[1].node) {
1364 (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", tam.ty, tam.mutbl),
1365 (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", tam.ty, MutImmutable),
1370 let mutbl = match mutbl {
1372 MutMutable => "_mut",
1374 let arg = match arg.node {
1375 ExprAddrOf(_, ref expr) => &**expr,
1379 if match_type(cx, ty, &paths::HASHMAP) || match_type(cx, ty, &paths::BTREEMAP) {
1384 &format!("you seem to want to iterate on a map's {}s", kind),
1386 let map = sugg::Sugg::hir(cx, arg, "map");
1389 "use the corresponding method".into(),
1391 (pat_span, snippet(cx, new_pat_span, kind).into_owned()),
1392 (arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)),
1402 struct MutateDelegate {
1403 node_id_low: Option<NodeId>,
1404 node_id_high: Option<NodeId>,
1405 span_low: Option<Span>,
1406 span_high: Option<Span>,
1409 impl<'tcx> Delegate<'tcx> for MutateDelegate {
1410 fn consume(&mut self, _: NodeId, _: Span, _: cmt<'tcx>, _: ConsumeMode) {}
1412 fn matched_pat(&mut self, _: &Pat, _: cmt<'tcx>, _: MatchMode) {}
1414 fn consume_pat(&mut self, _: &Pat, _: cmt<'tcx>, _: ConsumeMode) {}
1416 fn borrow(&mut self, _: NodeId, sp: Span, cmt: cmt<'tcx>, _: ty::Region, bk: ty::BorrowKind, _: LoanCause) {
1417 if let ty::BorrowKind::MutBorrow = bk {
1418 if let Categorization::Local(id) = cmt.cat {
1419 if Some(id) == self.node_id_low {
1420 self.span_low = Some(sp)
1422 if Some(id) == self.node_id_high {
1423 self.span_high = Some(sp)
1429 fn mutate(&mut self, _: NodeId, sp: Span, cmt: cmt<'tcx>, _: MutateMode) {
1430 if let Categorization::Local(id) = cmt.cat {
1431 if Some(id) == self.node_id_low {
1432 self.span_low = Some(sp)
1434 if Some(id) == self.node_id_high {
1435 self.span_high = Some(sp)
1440 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
1443 impl<'tcx> MutateDelegate {
1444 fn mutation_span(&self) -> (Option<Span>, Option<Span>) {
1445 (self.span_low, self.span_high)
1449 fn check_for_mut_range_bound(cx: &LateContext, arg: &Expr, body: &Expr) {
1450 if let Some(higher::Range {
1454 }) = higher::range(arg)
1457 check_for_mutability(cx, start),
1458 check_for_mutability(cx, end),
1460 if mut_ids[0].is_some() || mut_ids[1].is_some() {
1461 let (span_low, span_high) = check_for_mutation(cx, body, &mut_ids);
1462 mut_warn_with_span(cx, span_low);
1463 mut_warn_with_span(cx, span_high);
1468 fn mut_warn_with_span(cx: &LateContext, span: Option<Span>) {
1469 if let Some(sp) = span {
1474 "attempt to mutate range bound within loop; note that the range of the loop is unchanged",
1479 fn check_for_mutability(cx: &LateContext, bound: &Expr) -> Option<NodeId> {
1481 if let ExprPath(ref qpath) = bound.node;
1482 if let QPath::Resolved(None, _) = *qpath;
1484 let def = cx.tables.qpath_def(qpath, bound.hir_id);
1485 if let Def::Local(node_id) = def {
1486 let node_str = cx.tcx.hir.get(node_id);
1488 if let map::Node::NodeBinding(pat) = node_str;
1489 if let PatKind::Binding(bind_ann, _, _, _) = pat.node;
1490 if let BindingAnnotation::Mutable = bind_ann;
1492 return Some(node_id);
1501 fn check_for_mutation(cx: &LateContext, body: &Expr, bound_ids: &[Option<NodeId>]) -> (Option<Span>, Option<Span>) {
1502 let mut delegate = MutateDelegate {
1503 node_id_low: bound_ids[0],
1504 node_id_high: bound_ids[1],
1508 let def_id = def_id::DefId::local(body.hir_id.owner);
1509 let region_scope_tree = &cx.tcx.region_scope_tree(def_id);
1510 ExprUseVisitor::new(&mut delegate, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None).walk_expr(body);
1511 delegate.mutation_span()
1514 /// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`.
1515 fn pat_is_wild<'tcx>(pat: &'tcx PatKind, body: &'tcx Expr) -> bool {
1517 PatKind::Wild => true,
1518 PatKind::Binding(_, _, ident, None) if ident.node.as_str().starts_with('_') => {
1519 let mut visitor = UsedVisitor {
1523 walk_expr(&mut visitor, body);
1530 struct UsedVisitor {
1531 var: ast::Name, // var to look for
1532 used: bool, // has the var been used otherwise?
1535 impl<'tcx> Visitor<'tcx> for UsedVisitor {
1536 fn visit_expr(&mut self, expr: &'tcx Expr) {
1537 if match_var(expr, self.var) {
1540 walk_expr(self, expr);
1544 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1545 NestedVisitorMap::None
1549 struct LocalUsedVisitor<'a, 'tcx: 'a> {
1550 cx: &'a LateContext<'a, 'tcx>,
1555 impl<'a, 'tcx: 'a> Visitor<'tcx> for LocalUsedVisitor<'a, 'tcx> {
1556 fn visit_expr(&mut self, expr: &'tcx Expr) {
1557 if same_var(self.cx, expr, self.local) {
1560 walk_expr(self, expr);
1564 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1565 NestedVisitorMap::None
1569 struct VarVisitor<'a, 'tcx: 'a> {
1570 /// context reference
1571 cx: &'a LateContext<'a, 'tcx>,
1572 /// var name to look for as index
1574 /// indexed variables that are used mutably
1575 indexed_mut: HashSet<Name>,
1576 /// indirectly indexed variables (`v[(i + 4) % N]`), the extend is `None` for global
1577 indexed_indirectly: HashMap<Name, Option<region::Scope>>,
1578 /// subset of `indexed` of vars that are indexed directly: `v[i]`
1579 /// this will not contain cases like `v[calc_index(i)]` or `v[(i + 4) % N]`
1580 indexed_directly: HashMap<Name, Option<region::Scope>>,
1581 /// Any names that are used outside an index operation.
1582 /// Used to detect things like `&mut vec` used together with `vec[i]`
1583 referenced: HashSet<Name>,
1584 /// has the loop variable been used in expressions other than the index of
1587 /// Whether we are inside the `$` in `&mut $` or `$ = foo` or `$.bar`, where bar
1588 /// takes `&mut self`
1589 prefer_mutable: bool,
1592 impl<'a, 'tcx> VarVisitor<'a, 'tcx> {
1593 fn check(&mut self, idx: &'tcx Expr, seqexpr: &'tcx Expr, expr: &'tcx Expr) -> bool {
1595 // the indexed container is referenced by a name
1596 if let ExprPath(ref seqpath) = seqexpr.node;
1597 if let QPath::Resolved(None, ref seqvar) = *seqpath;
1598 if seqvar.segments.len() == 1;
1600 let index_used_directly = same_var(self.cx, idx, self.var);
1601 let indexed_indirectly = {
1602 let mut used_visitor = LocalUsedVisitor {
1607 walk_expr(&mut used_visitor, idx);
1611 if indexed_indirectly || index_used_directly {
1612 if self.prefer_mutable {
1613 self.indexed_mut.insert(seqvar.segments[0].name);
1615 let def = self.cx.tables.qpath_def(seqpath, seqexpr.hir_id);
1617 Def::Local(node_id) | Def::Upvar(node_id, ..) => {
1618 let hir_id = self.cx.tcx.hir.node_to_hir_id(node_id);
1620 let parent_id = self.cx.tcx.hir.get_parent(expr.id);
1621 let parent_def_id = self.cx.tcx.hir.local_def_id(parent_id);
1622 let extent = self.cx.tcx.region_scope_tree(parent_def_id).var_scope(hir_id.local_id);
1623 if indexed_indirectly {
1624 self.indexed_indirectly.insert(seqvar.segments[0].name, Some(extent));
1626 if index_used_directly {
1627 self.indexed_directly.insert(seqvar.segments[0].name, Some(extent));
1629 return false; // no need to walk further *on the variable*
1631 Def::Static(..) | Def::Const(..) => {
1632 if indexed_indirectly {
1633 self.indexed_indirectly.insert(seqvar.segments[0].name, None);
1635 if index_used_directly {
1636 self.indexed_directly.insert(seqvar.segments[0].name, None);
1638 return false; // no need to walk further *on the variable*
1649 impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
1650 fn visit_expr(&mut self, expr: &'tcx Expr) {
1653 if let ExprMethodCall(ref meth, _, ref args) = expr.node;
1654 if meth.name == "index" || meth.name == "index_mut";
1655 if !self.check(&args[1], &args[0], expr);
1661 if let ExprIndex(ref seqexpr, ref idx) = expr.node;
1662 if !self.check(idx, seqexpr, expr);
1667 // directly using a variable
1668 if let ExprPath(ref qpath) = expr.node;
1669 if let QPath::Resolved(None, ref path) = *qpath;
1670 if path.segments.len() == 1;
1671 if let Def::Local(local_id) = self.cx.tables.qpath_def(qpath, expr.hir_id);
1673 if local_id == self.var {
1674 // we are not indexing anything, record that
1675 self.nonindex = true;
1677 // not the correct variable, but still a variable
1678 self.referenced.insert(path.segments[0].name);
1682 let old = self.prefer_mutable;
1684 ExprAssignOp(_, ref lhs, ref rhs) |
1685 ExprAssign(ref lhs, ref rhs) => {
1686 self.prefer_mutable = true;
1687 self.visit_expr(lhs);
1688 self.prefer_mutable = false;
1689 self.visit_expr(rhs);
1691 ExprAddrOf(mutbl, ref expr) => {
1692 if mutbl == MutMutable {
1693 self.prefer_mutable = true;
1695 self.visit_expr(expr);
1697 ExprCall(ref f, ref args) => {
1700 let ty = self.cx.tables.expr_ty_adjusted(expr);
1701 self.prefer_mutable = false;
1702 if let ty::TyRef(_, mutbl) = ty.sty {
1703 if mutbl.mutbl == MutMutable {
1704 self.prefer_mutable = true;
1707 self.visit_expr(expr);
1710 ExprMethodCall(_, _, ref args) => {
1711 let def_id = self.cx.tables.type_dependent_defs()[expr.hir_id].def_id();
1712 for (ty, expr) in self.cx.tcx.fn_sig(def_id).inputs().skip_binder().iter().zip(args) {
1713 self.prefer_mutable = false;
1714 if let ty::TyRef(_, mutbl) = ty.sty {
1715 if mutbl.mutbl == MutMutable {
1716 self.prefer_mutable = true;
1719 self.visit_expr(expr);
1722 _ => walk_expr(self, expr),
1724 self.prefer_mutable = old;
1726 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1727 NestedVisitorMap::None
1731 fn is_iterator_used_after_while_let<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, iter_expr: &'tcx Expr) -> bool {
1732 let def_id = match var_def_id(cx, iter_expr) {
1734 None => return false,
1736 let mut visitor = VarUsedAfterLoopVisitor {
1739 iter_expr_id: iter_expr.id,
1740 past_while_let: false,
1741 var_used_after_while_let: false,
1743 if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
1744 walk_block(&mut visitor, enclosing_block);
1746 visitor.var_used_after_while_let
1749 struct VarUsedAfterLoopVisitor<'a, 'tcx: 'a> {
1750 cx: &'a LateContext<'a, 'tcx>,
1752 iter_expr_id: NodeId,
1753 past_while_let: bool,
1754 var_used_after_while_let: bool,
1757 impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
1758 fn visit_expr(&mut self, expr: &'tcx Expr) {
1759 if self.past_while_let {
1760 if Some(self.def_id) == var_def_id(self.cx, expr) {
1761 self.var_used_after_while_let = true;
1763 } else if self.iter_expr_id == expr.id {
1764 self.past_while_let = true;
1766 walk_expr(self, expr);
1768 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1769 NestedVisitorMap::None
1774 /// Return true if the type of expr is one that provides `IntoIterator` impls
1775 /// for `&T` and `&mut T`, such as `Vec`.
1776 #[cfg_attr(rustfmt, rustfmt_skip)]
1777 fn is_ref_iterable_type(cx: &LateContext, e: &Expr) -> bool {
1778 // no walk_ptrs_ty: calling iter() on a reference can make sense because it
1779 // will allow further borrows afterwards
1780 let ty = cx.tables.expr_ty(e);
1781 is_iterable_array(ty) ||
1782 match_type(cx, ty, &paths::VEC) ||
1783 match_type(cx, ty, &paths::LINKED_LIST) ||
1784 match_type(cx, ty, &paths::HASHMAP) ||
1785 match_type(cx, ty, &paths::HASHSET) ||
1786 match_type(cx, ty, &paths::VEC_DEQUE) ||
1787 match_type(cx, ty, &paths::BINARY_HEAP) ||
1788 match_type(cx, ty, &paths::BTREEMAP) ||
1789 match_type(cx, ty, &paths::BTREESET)
1792 fn is_iterable_array(ty: Ty) -> bool {
1793 // IntoIterator is currently only implemented for array sizes <= 32 in rustc
1795 ty::TyArray(_, n) => (0..=32).contains(const_to_u64(n)),
1800 /// If a block begins with a statement (possibly a `let` binding) and has an
1801 /// expression, return it.
1802 fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
1803 if block.stmts.is_empty() {
1806 if let StmtDecl(ref decl, _) = block.stmts[0].node {
1807 if let DeclLocal(ref local) = decl.node {
1808 if let Some(ref expr) = local.init {
1821 /// If a block begins with an expression (with or without semicolon), return it.
1822 fn extract_first_expr(block: &Block) -> Option<&Expr> {
1824 Some(ref expr) if block.stmts.is_empty() => Some(expr),
1825 None if !block.stmts.is_empty() => match block.stmts[0].node {
1826 StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => Some(expr),
1827 StmtDecl(..) => None,
1833 /// Return true if expr contains a single break expr without destination label
1835 /// passed expression. The expression may be within a block.
1836 fn is_simple_break_expr(expr: &Expr) -> bool {
1838 ExprBreak(dest, ref passed_expr) if dest.label.is_none() && passed_expr.is_none() => true,
1839 ExprBlock(ref b) => match extract_first_expr(b) {
1840 Some(subexpr) => is_simple_break_expr(subexpr),
1847 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
1848 // incremented exactly once in the loop body, and initialized to zero
1849 // at the start of the loop.
1850 #[derive(PartialEq)]
1852 Initial, // Not examined yet
1853 IncrOnce, // Incremented exactly once, may be a loop counter
1854 Declared, // Declared but not (yet) initialized to zero
1859 /// Scan a for loop for variables that are incremented exactly once.
1860 struct IncrementVisitor<'a, 'tcx: 'a> {
1861 cx: &'a LateContext<'a, 'tcx>, // context reference
1862 states: HashMap<NodeId, VarState>, // incremented variables
1863 depth: u32, // depth of conditional expressions
1867 impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
1868 fn visit_expr(&mut self, expr: &'tcx Expr) {
1873 // If node is a variable
1874 if let Some(def_id) = var_def_id(self.cx, expr) {
1875 if let Some(parent) = get_parent_expr(self.cx, expr) {
1876 let state = self.states.entry(def_id).or_insert(VarState::Initial);
1879 ExprAssignOp(op, ref lhs, ref rhs) => {
1880 if lhs.id == expr.id {
1881 if op.node == BiAdd && is_integer_literal(rhs, 1) {
1882 *state = match *state {
1883 VarState::Initial if self.depth == 0 => VarState::IncrOnce,
1884 _ => VarState::DontWarn,
1887 // Assigned some other value
1888 *state = VarState::DontWarn;
1892 ExprAssign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
1893 ExprAddrOf(mutability, _) if mutability == MutMutable => *state = VarState::DontWarn,
1897 } else if is_loop(expr) {
1898 self.states.clear();
1901 } else if is_conditional(expr) {
1903 walk_expr(self, expr);
1907 walk_expr(self, expr);
1909 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1910 NestedVisitorMap::None
1914 /// Check whether a variable is initialized to zero at the start of a loop.
1915 struct InitializeVisitor<'a, 'tcx: 'a> {
1916 cx: &'a LateContext<'a, 'tcx>, // context reference
1917 end_expr: &'tcx Expr, // the for loop. Stop scanning here.
1921 depth: u32, // depth of conditional expressions
1925 impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
1926 fn visit_decl(&mut self, decl: &'tcx Decl) {
1927 // Look for declarations of the variable
1928 if let DeclLocal(ref local) = decl.node {
1929 if local.pat.id == self.var_id {
1930 if let PatKind::Binding(_, _, ref ident, _) = local.pat.node {
1931 self.name = Some(ident.node);
1933 self.state = if let Some(ref init) = local.init {
1934 if is_integer_literal(init, 0) {
1945 walk_decl(self, decl);
1948 fn visit_expr(&mut self, expr: &'tcx Expr) {
1949 if self.state == VarState::DontWarn {
1952 if expr == self.end_expr {
1953 self.past_loop = true;
1956 // No need to visit expressions before the variable is
1958 if self.state == VarState::IncrOnce {
1962 // If node is the desired variable, see how it's used
1963 if var_def_id(self.cx, expr) == Some(self.var_id) {
1964 if let Some(parent) = get_parent_expr(self.cx, expr) {
1966 ExprAssignOp(_, ref lhs, _) if lhs.id == expr.id => {
1967 self.state = VarState::DontWarn;
1969 ExprAssign(ref lhs, ref rhs) if lhs.id == expr.id => {
1970 self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
1976 ExprAddrOf(mutability, _) if mutability == MutMutable => self.state = VarState::DontWarn,
1982 self.state = VarState::DontWarn;
1985 } else if !self.past_loop && is_loop(expr) {
1986 self.state = VarState::DontWarn;
1988 } else if is_conditional(expr) {
1990 walk_expr(self, expr);
1994 walk_expr(self, expr);
1996 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1997 NestedVisitorMap::None
2001 fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
2002 if let ExprPath(ref qpath) = expr.node {
2003 let path_res = cx.tables.qpath_def(qpath, expr.hir_id);
2004 if let Def::Local(node_id) = path_res {
2005 return Some(node_id);
2011 fn is_loop(expr: &Expr) -> bool {
2013 ExprLoop(..) | ExprWhile(..) => true,
2018 fn is_conditional(expr: &Expr) -> bool {
2020 ExprIf(..) | ExprMatch(..) => true,
2025 fn is_nested(cx: &LateContext, match_expr: &Expr, iter_expr: &Expr) -> bool {
2027 if let Some(loop_block) = get_enclosing_block(cx, match_expr.id);
2028 if let Some(map::Node::NodeExpr(loop_expr)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(loop_block.id));
2030 return is_loop_nested(cx, loop_expr, iter_expr)
2036 fn is_loop_nested(cx: &LateContext, loop_expr: &Expr, iter_expr: &Expr) -> bool {
2037 let mut id = loop_expr.id;
2038 let iter_name = if let Some(name) = path_name(iter_expr) {
2044 let parent = cx.tcx.hir.get_parent_node(id);
2048 match cx.tcx.hir.find(parent) {
2049 Some(NodeExpr(expr)) => match expr.node {
2050 ExprLoop(..) | ExprWhile(..) => {
2055 Some(NodeBlock(block)) => {
2056 let mut block_visitor = LoopNestVisitor {
2058 iterator: iter_name,
2061 walk_block(&mut block_visitor, block);
2062 if block_visitor.nesting == RuledOut {
2066 Some(NodeStmt(_)) => (),
2075 #[derive(PartialEq, Eq)]
2077 Unknown, // no nesting detected yet
2078 RuledOut, // the iterator is initialized or assigned within scope
2079 LookFurther, // no nesting detected, no further walk required
2082 use self::Nesting::{LookFurther, RuledOut, Unknown};
2084 struct LoopNestVisitor {
2090 impl<'tcx> Visitor<'tcx> for LoopNestVisitor {
2091 fn visit_stmt(&mut self, stmt: &'tcx Stmt) {
2092 if stmt.node.id() == self.id {
2093 self.nesting = LookFurther;
2094 } else if self.nesting == Unknown {
2095 walk_stmt(self, stmt);
2099 fn visit_expr(&mut self, expr: &'tcx Expr) {
2100 if self.nesting != Unknown {
2103 if expr.id == self.id {
2104 self.nesting = LookFurther;
2108 ExprAssign(ref path, _) | ExprAssignOp(_, ref path, _) => if match_var(path, self.iterator) {
2109 self.nesting = RuledOut;
2111 _ => walk_expr(self, expr),
2115 fn visit_pat(&mut self, pat: &'tcx Pat) {
2116 if self.nesting != Unknown {
2119 if let PatKind::Binding(_, _, span_name, _) = pat.node {
2120 if self.iterator == span_name.node {
2121 self.nesting = RuledOut;
2128 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2129 NestedVisitorMap::None
2133 fn path_name(e: &Expr) -> Option<Name> {
2134 if let ExprPath(QPath::Resolved(_, ref path)) = e.node {
2135 let segments = &path.segments;
2136 if segments.len() == 1 {
2137 return Some(segments[0].name);
2143 fn check_infinite_loop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, cond: &'tcx Expr, block: &'tcx Block, expr: &'tcx Expr) {
2144 let mut mut_var_visitor = MutableVarsVisitor {
2146 ids: HashSet::new(),
2149 walk_expr(&mut mut_var_visitor, expr);
2150 if mut_var_visitor.skip {
2154 if mut_var_visitor.ids.len() == 0 {
2157 WHILE_IMMUTABLE_CONDITION,
2159 "all variables in condition are immutable. This might lead to infinite loops.",
2164 let mut use_visitor = MutablyUsedVisitor {
2166 ids: mut_var_visitor.ids,
2169 walk_block(&mut use_visitor, block);
2170 if !use_visitor.any_used {
2173 WHILE_IMMUTABLE_CONDITION,
2175 "Variable in the condition are not mutated in the loop body. This might lead to infinite loops.",
2180 /// Collects the set of mutable variable in an expression
2181 /// Stops analysis if a function call is found
2182 struct MutableVarsVisitor<'a, 'tcx: 'a> {
2183 cx: &'a LateContext<'a, 'tcx>,
2184 ids: HashSet<NodeId>,
2188 impl<'a, 'tcx> Visitor<'tcx> for MutableVarsVisitor<'a, 'tcx> {
2189 fn visit_expr(&mut self, ex: &'tcx Expr) {
2191 ExprPath(_) => if let Some(node_id) = check_for_mutability(self.cx, &ex) {
2192 self.ids.insert(node_id);
2195 // If there is any fuction/method call… we just stop analysis
2196 ExprCall(..) | ExprMethodCall(..) => self.skip = true,
2198 _ => walk_expr(self, ex),
2202 fn visit_block(&mut self, _b: &'tcx Block) {}
2204 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2205 NestedVisitorMap::None
2209 /// checks within an expression/statement if any of the variables are used mutably
2210 struct MutablyUsedVisitor<'a, 'tcx: 'a> {
2211 cx: &'a LateContext<'a, 'tcx>,
2212 ids: HashSet<NodeId>,
2216 impl<'a, 'tcx> Visitor<'tcx> for MutablyUsedVisitor<'a, 'tcx> {
2217 fn visit_expr(&mut self, ex: &'tcx Expr) {
2218 if self.any_used { return; }
2221 ExprAddrOf(MutMutable, ref p) | ExprAssign(ref p, _) | ExprAssignOp(_, ref p, _) =>
2222 if let Some(id) = check_for_mutability(self.cx, p) {
2223 self.any_used = self.ids.contains(&id);
2225 _ => walk_expr(self, ex)
2229 fn visit_stmt(&mut self, s: &'tcx Stmt) {
2231 StmtExpr(..) | StmtSemi (..) => walk_stmt(self, s),
2236 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2237 NestedVisitorMap::None