1 use itertools::Itertools;
2 use crate::reexport::*;
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::region;
10 // use rustc::middle::region::CodeExtent;
11 use rustc::middle::expr_use_visitor::*;
12 use rustc::middle::mem_categorization::Categorization;
13 use rustc::middle::mem_categorization::cmt_;
14 use rustc::ty::{self, Ty};
15 use rustc::ty::subst::Subst;
16 use std::collections::{HashMap, HashSet};
17 use std::iter::{once, Iterator};
19 use syntax::codemap::Span;
20 use crate::utils::{sugg, sext};
21 use crate::utils::usage::mutated_variables;
22 use crate::consts::{constant, Constant};
24 use crate::utils::{get_enclosing_block, get_parent_expr, higher, in_external_macro, is_integer_literal, is_refutable,
25 last_path_segment, match_trait_method, match_type, match_var, multispan_sugg, snippet, snippet_opt,
26 span_help_and_lint, span_lint, span_lint_and_sugg, span_lint_and_then};
27 use crate::utils::paths;
29 /// **What it does:** Checks for for-loops that manually copy items between
30 /// slices that could be optimized by having a memcpy.
32 /// **Why is this bad?** It is not as fast as a memcpy.
34 /// **Known problems:** None.
38 /// for i in 0..src.len() {
39 /// dst[i + 64] = src[i];
42 declare_clippy_lint! {
45 "manually copying items between slices"
48 /// **What it does:** Checks for looping over the range of `0..len` of some
49 /// collection just to get the values by index.
51 /// **Why is this bad?** Just iterating the collection itself makes the intent
52 /// more clear and is probably faster.
54 /// **Known problems:** None.
58 /// for i in 0..vec.len() {
59 /// println!("{}", vec[i]);
62 declare_clippy_lint! {
63 pub NEEDLESS_RANGE_LOOP,
65 "for-looping over a range of indices where an iterator over items would do"
68 /// **What it does:** Checks for loops on `x.iter()` where `&x` will do, and
69 /// suggests the latter.
71 /// **Why is this bad?** Readability.
73 /// **Known problems:** False negatives. We currently only warn on some known
78 /// // with `y` a `Vec` or slice:
79 /// for x in y.iter() { .. }
81 declare_clippy_lint! {
82 pub EXPLICIT_ITER_LOOP,
84 "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
87 /// **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and
88 /// suggests the latter.
90 /// **Why is this bad?** Readability.
92 /// **Known problems:** None
96 /// // with `y` a `Vec` or slice:
97 /// for x in y.into_iter() { .. }
99 declare_clippy_lint! {
100 pub EXPLICIT_INTO_ITER_LOOP,
102 "for-looping over `_.into_iter()` when `_` would do"
105 /// **What it does:** Checks for loops on `x.next()`.
107 /// **Why is this bad?** `next()` returns either `Some(value)` if there was a
108 /// value, or `None` otherwise. The insidious thing is that `Option<_>`
109 /// implements `IntoIterator`, so that possibly one value will be iterated,
110 /// leading to some hard to find bugs. No one will want to write such code
111 /// [except to win an Underhanded Rust
112 /// Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
114 /// **Known problems:** None.
118 /// for x in y.next() { .. }
120 declare_clippy_lint! {
123 "for-looping over `_.next()` which is probably not intended"
126 /// **What it does:** Checks for `for` loops over `Option` values.
128 /// **Why is this bad?** Readability. This is more clearly expressed as an `if
131 /// **Known problems:** None.
135 /// for x in option { .. }
140 /// if let Some(x) = option { .. }
142 declare_clippy_lint! {
143 pub FOR_LOOP_OVER_OPTION,
145 "for-looping over an `Option`, which is more clearly expressed as an `if let`"
148 /// **What it does:** Checks for `for` loops over `Result` values.
150 /// **Why is this bad?** Readability. This is more clearly expressed as an `if
153 /// **Known problems:** None.
157 /// for x in result { .. }
162 /// if let Ok(x) = result { .. }
164 declare_clippy_lint! {
165 pub FOR_LOOP_OVER_RESULT,
167 "for-looping over a `Result`, which is more clearly expressed as an `if let`"
170 /// **What it does:** Detects `loop + match` combinations that are easier
171 /// written as a `while let` loop.
173 /// **Why is this bad?** The `while let` loop is usually shorter and more
176 /// **Known problems:** Sometimes the wrong binding is displayed (#383).
181 /// let x = match y {
185 /// // .. do something with x
187 /// // is easier written as
188 /// while let Some(x) = y {
189 /// // .. do something with x
192 declare_clippy_lint! {
195 "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
198 /// **What it does:** Checks for using `collect()` on an iterator without using
201 /// **Why is this bad?** It is more idiomatic to use a `for` loop over the
202 /// iterator instead.
204 /// **Known problems:** None.
208 /// vec.iter().map(|x| /* some operation returning () */).collect::<Vec<_>>();
210 declare_clippy_lint! {
213 "`collect()`ing an iterator without using the result; this is usually better \
214 written as a for loop"
217 /// **What it does:** Checks for loops over ranges `x..y` where both `x` and `y`
218 /// are constant and `x` is greater or equal to `y`, unless the range is
219 /// reversed or has a negative `.step_by(_)`.
221 /// **Why is it bad?** Such loops will either be skipped or loop until
222 /// wrap-around (in debug code, this may `panic!()`). Both options are probably
225 /// **Known problems:** The lint cannot catch loops over dynamically defined
226 /// ranges. Doing this would require simulating all possible inputs and code
227 /// paths through the program, which would be complex and error-prone.
231 /// for x in 5..10-5 { .. } // oops, stray `-`
233 declare_clippy_lint! {
234 pub REVERSE_RANGE_LOOP,
236 "iteration over an empty range, such as `10..0` or `5..5`"
239 /// **What it does:** Checks `for` loops over slices with an explicit counter
240 /// and suggests the use of `.enumerate()`.
242 /// **Why is it bad?** Not only is the version using `.enumerate()` more
243 /// readable, the compiler is able to remove bounds checks which can lead to
244 /// faster code in some instances.
246 /// **Known problems:** None.
250 /// for i in 0..v.len() { foo(v[i]);
251 /// for i in 0..v.len() { bar(i, v[i]); }
253 declare_clippy_lint! {
254 pub EXPLICIT_COUNTER_LOOP,
256 "for-looping with an explicit counter when `_.enumerate()` would do"
259 /// **What it does:** Checks for empty `loop` expressions.
261 /// **Why is this bad?** Those busy loops burn CPU cycles without doing
262 /// anything. Think of the environment and either block on something or at least
263 /// make the thread sleep for some microseconds.
265 /// **Known problems:** None.
271 declare_clippy_lint! {
274 "empty `loop {}`, which should block or sleep"
277 /// **What it does:** Checks for `while let` expressions on iterators.
279 /// **Why is this bad?** Readability. A simple `for` loop is shorter and conveys
280 /// the intent better.
282 /// **Known problems:** None.
286 /// while let Some(val) = iter() { .. }
288 declare_clippy_lint! {
289 pub WHILE_LET_ON_ITERATOR,
291 "using a while-let loop instead of a for loop on an iterator"
294 /// **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and
295 /// ignoring either the keys or values.
297 /// **Why is this bad?** Readability. There are `keys` and `values` methods that
298 /// can be used to express that don't need the values or keys.
300 /// **Known problems:** None.
304 /// for (k, _) in &map { .. }
307 /// could be replaced by
310 /// for k in map.keys() { .. }
312 declare_clippy_lint! {
315 "looping on a map using `iter` when `keys` or `values` would do"
318 /// **What it does:** Checks for loops that will always `break`, `return` or
319 /// `continue` an outer loop.
321 /// **Why is this bad?** This loop never loops, all it does is obfuscating the
324 /// **Known problems:** None
328 /// loop { ..; break; }
330 declare_clippy_lint! {
333 "any loop that will always `break` or `return`"
336 /// **What it does:** Checks for loops which have a range bound that is a mutable variable
338 /// **Why is this bad?** One might think that modifying the mutable variable changes the loop bounds
340 /// **Known problems:** None
344 /// let mut foo = 42;
345 /// for i in 0..foo {
347 /// println!("{}", i); // prints numbers from 0 to 42, not 0 to 21
350 declare_clippy_lint! {
353 "for loop over a range where one of the bounds is a mutable variable"
356 /// **What it does:** Checks whether variables used within while loop condition
357 /// can be (and are) mutated in the body.
359 /// **Why is this bad?** If the condition is unchanged, entering the body of the loop
360 /// will lead to an infinite loop.
362 /// **Known problems:** If the `while`-loop is in a closure, the check for mutation of the
363 /// condition variables in the body can cause false negatives. For example when only `Upvar` `a` is
364 /// in the condition and only `Upvar` `b` gets mutated in the body, the lint will not trigger.
370 /// println!("let me loop forever!");
373 declare_clippy_lint! {
374 pub WHILE_IMMUTABLE_CONDITION,
376 "variables used within while expression are not mutated in the body"
379 #[derive(Copy, Clone)]
382 impl LintPass for Pass {
383 fn get_lints(&self) -> LintArray {
388 EXPLICIT_INTO_ITER_LOOP,
390 FOR_LOOP_OVER_RESULT,
391 FOR_LOOP_OVER_OPTION,
395 EXPLICIT_COUNTER_LOOP,
397 WHILE_LET_ON_ITERATOR,
401 WHILE_IMMUTABLE_CONDITION,
406 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
407 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
408 if let Some((pat, arg, body)) = higher::for_loop(expr) {
409 check_for_loop(cx, pat, arg, body, expr);
412 // check for never_loop
414 ExprWhile(_, ref block, _) | ExprLoop(ref block, _, _) => {
415 match never_loop_block(block, expr.id) {
416 NeverLoopResult::AlwaysBreak =>
417 span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops"),
418 NeverLoopResult::MayContinueMainLoop | NeverLoopResult::Otherwise => (),
424 // check for `loop { if let {} else break }` that could be `while let`
425 // (also matches an explicit "match" instead of "if let")
426 // (even if the "match" or "if let" is used for declaration)
427 if let ExprLoop(ref block, _, LoopSource::Loop) = expr.node {
428 // also check for empty `loop {}` statements
429 if block.stmts.is_empty() && block.expr.is_none() {
434 "empty `loop {}` detected. You may want to either use `panic!()` or add \
435 `std::thread::sleep(..);` to the loop body.",
439 // extract the expression from the first statement (if any) in a block
440 let inner_stmt_expr = extract_expr_from_first_stmt(block);
441 // or extract the first expression (if any) from the block
442 if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
443 if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node {
444 // ensure "if let" compatible match structure
446 MatchSource::Normal | MatchSource::IfLetDesugar { .. } => {
447 if arms.len() == 2 && arms[0].pats.len() == 1 && arms[0].guard.is_none()
448 && arms[1].pats.len() == 1 && arms[1].guard.is_none()
449 && is_simple_break_expr(&arms[1].body)
451 if in_external_macro(cx, expr.span) {
455 // NOTE: we used to make build a body here instead of using
456 // ellipsis, this was removed because:
457 // 1) it was ugly with big bodies;
458 // 2) it was not indented properly;
459 // 3) it wasn’t very smart (see #675).
464 "this loop could be written as a `while let` loop",
467 "while let {} = {} {{ .. }}",
468 snippet(cx, arms[0].pats[0].span, ".."),
469 snippet(cx, matchexpr.span, "..")
479 if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
480 let pat = &arms[0].pats[0].node;
482 &PatKind::TupleStruct(ref qpath, ref pat_args, _),
483 &ExprMethodCall(ref method_path, _, ref method_args),
484 ) = (pat, &match_expr.node)
486 let iter_expr = &method_args[0];
487 let lhs_constructor = last_path_segment(qpath);
488 if method_path.name == "next" && match_trait_method(cx, match_expr, &paths::ITERATOR)
489 && lhs_constructor.name == "Some" && !is_refutable(cx, &pat_args[0])
490 && !is_iterator_used_after_while_let(cx, iter_expr)
491 && !is_nested(cx, expr, &method_args[0])
493 let iterator = snippet(cx, method_args[0].span, "_");
494 let loop_var = snippet(cx, pat_args[0].span, "_");
497 WHILE_LET_ON_ITERATOR,
499 "this loop could be written as a `for` loop",
501 format!("for {} in {} {{ .. }}", loop_var, iterator),
507 // check for while loops which conditions never change
508 if let ExprWhile(ref cond, _, _) = expr.node {
509 check_infinite_loop(cx, cond, expr);
513 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
514 if let StmtSemi(ref expr, _) = stmt.node {
515 if let ExprMethodCall(ref method, _, ref args) = expr.node {
516 if args.len() == 1 && method.name == "collect" && match_trait_method(cx, expr, &paths::ITERATOR) {
521 "you are collect()ing an iterator and throwing away the result. \
522 Consider using an explicit for loop to exhaust the iterator",
530 enum NeverLoopResult {
531 // A break/return always get triggered but not necessarily for the main loop.
533 // A continue may occur for the main loop.
538 fn absorb_break(arg: &NeverLoopResult) -> NeverLoopResult {
540 NeverLoopResult::AlwaysBreak |
541 NeverLoopResult::Otherwise => NeverLoopResult::Otherwise,
542 NeverLoopResult::MayContinueMainLoop => NeverLoopResult::MayContinueMainLoop,
546 // Combine two results for parts that are called in order.
547 fn combine_seq(first: NeverLoopResult, second: NeverLoopResult) -> NeverLoopResult {
549 NeverLoopResult::AlwaysBreak | NeverLoopResult::MayContinueMainLoop => first,
550 NeverLoopResult::Otherwise => second,
554 // Combine two results where both parts are called but not necessarily in order.
555 fn combine_both(left: NeverLoopResult, right: NeverLoopResult) -> NeverLoopResult {
556 match (left, right) {
557 (NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) =>
558 NeverLoopResult::MayContinueMainLoop,
559 (NeverLoopResult::AlwaysBreak, _) | (_, NeverLoopResult::AlwaysBreak) =>
560 NeverLoopResult::AlwaysBreak,
561 (NeverLoopResult::Otherwise, NeverLoopResult::Otherwise) =>
562 NeverLoopResult::Otherwise,
566 // Combine two results where only one of the part may have been executed.
567 fn combine_branches(b1: NeverLoopResult, b2: NeverLoopResult) -> NeverLoopResult {
569 (NeverLoopResult::AlwaysBreak, NeverLoopResult::AlwaysBreak) =>
570 NeverLoopResult::AlwaysBreak,
571 (NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) =>
572 NeverLoopResult::MayContinueMainLoop,
573 (NeverLoopResult::Otherwise, _) | (_, NeverLoopResult::Otherwise) =>
574 NeverLoopResult::Otherwise,
578 fn never_loop_block(block: &Block, main_loop_id: NodeId) -> NeverLoopResult {
579 let stmts = block.stmts.iter().map(stmt_to_expr);
580 let expr = once(block.expr.as_ref().map(|p| &**p));
581 let mut iter = stmts.chain(expr).filter_map(|e| e);
582 never_loop_expr_seq(&mut iter, main_loop_id)
585 fn stmt_to_expr(stmt: &Stmt) -> Option<&Expr> {
587 StmtSemi(ref e, ..) | StmtExpr(ref e, ..) => Some(e),
588 StmtDecl(ref d, ..) => decl_to_expr(d),
592 fn decl_to_expr(decl: &Decl) -> Option<&Expr> {
594 DeclLocal(ref local) => local.init.as_ref().map(|p| &**p),
599 fn never_loop_expr(expr: &Expr, main_loop_id: NodeId) -> NeverLoopResult {
602 ExprUnary(_, ref e) |
605 ExprField(ref e, _) |
606 ExprAddrOf(_, ref e) |
607 ExprStruct(_, _, Some(ref e)) |
608 ExprRepeat(ref e, _) => never_loop_expr(e, main_loop_id),
609 ExprArray(ref es) | ExprMethodCall(_, _, ref es) | ExprTup(ref es) => {
610 never_loop_expr_all(&mut es.iter(), main_loop_id)
612 ExprCall(ref e, ref es) => never_loop_expr_all(&mut once(&**e).chain(es.iter()), main_loop_id),
613 ExprBinary(_, ref e1, ref e2) |
614 ExprAssign(ref e1, ref e2) |
615 ExprAssignOp(_, ref e1, ref e2) |
616 ExprIndex(ref e1, ref e2) => never_loop_expr_all(&mut [&**e1, &**e2].iter().cloned(), main_loop_id),
617 ExprIf(ref e, ref e2, ref e3) => {
618 let e1 = never_loop_expr(e, main_loop_id);
619 let e2 = never_loop_expr(e2, main_loop_id);
620 let e3 = e3.as_ref().map_or(NeverLoopResult::Otherwise, |e| never_loop_expr(e, main_loop_id));
621 combine_seq(e1, combine_branches(e2, e3))
623 ExprLoop(ref b, _, _) => {
624 // Break can come from the inner loop so remove them.
625 absorb_break(&never_loop_block(b, main_loop_id))
627 ExprWhile(ref e, ref b, _) => {
628 let e = never_loop_expr(e, main_loop_id);
629 let result = never_loop_block(b, main_loop_id);
630 // Break can come from the inner loop so remove them.
631 combine_seq(e, absorb_break(&result))
633 ExprMatch(ref e, ref arms, _) => {
634 let e = never_loop_expr(e, main_loop_id);
638 let arms = never_loop_expr_branch(&mut arms.iter().map(|a| &*a.body), main_loop_id);
642 ExprBlock(ref b, _) => never_loop_block(b, main_loop_id),
645 .expect("target id can only be missing in the presence of compilation errors");
646 if id == main_loop_id {
647 NeverLoopResult::MayContinueMainLoop
649 NeverLoopResult::AlwaysBreak
653 NeverLoopResult::AlwaysBreak
656 if let Some(ref e) = *e {
657 combine_seq(never_loop_expr(e, main_loop_id), NeverLoopResult::AlwaysBreak)
659 NeverLoopResult::AlwaysBreak
662 ExprStruct(_, _, None) |
664 ExprClosure(_, _, _, _, _) |
665 ExprInlineAsm(_, _, _) |
667 ExprLit(_) => NeverLoopResult::Otherwise,
671 fn never_loop_expr_seq<'a, T: Iterator<Item=&'a Expr>>(es: &mut T, main_loop_id: NodeId) -> NeverLoopResult {
672 es.map(|e| never_loop_expr(e, main_loop_id))
673 .fold(NeverLoopResult::Otherwise, combine_seq)
676 fn never_loop_expr_all<'a, T: Iterator<Item=&'a Expr>>(es: &mut T, main_loop_id: NodeId) -> NeverLoopResult {
677 es.map(|e| never_loop_expr(e, main_loop_id))
678 .fold(NeverLoopResult::Otherwise, combine_both)
681 fn never_loop_expr_branch<'a, T: Iterator<Item=&'a Expr>>(e: &mut T, main_loop_id: NodeId) -> NeverLoopResult {
682 e.map(|e| never_loop_expr(e, main_loop_id))
683 .fold(NeverLoopResult::AlwaysBreak, combine_branches)
686 fn check_for_loop<'a, 'tcx>(
687 cx: &LateContext<'a, 'tcx>,
693 check_for_loop_range(cx, pat, arg, body, expr);
694 check_for_loop_reverse_range(cx, arg, expr);
695 check_for_loop_arg(cx, pat, arg, expr);
696 check_for_loop_explicit_counter(cx, arg, body, expr);
697 check_for_loop_over_map_kv(cx, pat, arg, body, expr);
698 check_for_mut_range_bound(cx, arg, body);
699 detect_manual_memcpy(cx, pat, arg, body, expr);
702 fn same_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr, var: ast::NodeId) -> bool {
704 if let ExprPath(ref qpath) = expr.node;
705 if let QPath::Resolved(None, ref path) = *qpath;
706 if path.segments.len() == 1;
707 if let Def::Local(local_id) = cx.tables.qpath_def(qpath, expr.hir_id);
724 fn negative(s: String) -> Self {
731 fn positive(s: String) -> Self {
739 struct FixedOffsetVar {
744 fn is_slice_like<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty) -> bool {
745 let is_slice = match ty.sty {
746 ty::TyRef(_, subty, _) => is_slice_like(cx, subty),
747 ty::TySlice(..) | ty::TyArray(..) => true,
751 is_slice || match_type(cx, ty, &paths::VEC) || match_type(cx, ty, &paths::VEC_DEQUE)
754 fn get_fixed_offset_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr, var: ast::NodeId) -> Option<FixedOffsetVar> {
755 fn extract_offset<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &Expr, var: ast::NodeId) -> Option<String> {
757 ExprLit(ref l) => match l.node {
758 ast::LitKind::Int(x, _ty) => Some(x.to_string()),
761 ExprPath(..) if !same_var(cx, e, var) => Some(snippet_opt(cx, e.span).unwrap_or_else(|| "??".into())),
766 if let ExprIndex(ref seqexpr, ref idx) = expr.node {
767 let ty = cx.tables.expr_ty(seqexpr);
768 if !is_slice_like(cx, ty) {
772 let offset = match idx.node {
773 ExprBinary(op, ref lhs, ref rhs) => match op.node {
775 let offset_opt = if same_var(cx, lhs, var) {
776 extract_offset(cx, rhs, var)
777 } else if same_var(cx, rhs, var) {
778 extract_offset(cx, lhs, var)
783 offset_opt.map(Offset::positive)
785 BinOp_::BiSub if same_var(cx, lhs, var) => extract_offset(cx, rhs, var).map(Offset::negative),
788 ExprPath(..) => if same_var(cx, idx, var) {
789 Some(Offset::positive("0".into()))
798 var_name: snippet_opt(cx, seqexpr.span).unwrap_or_else(|| "???".into()),
807 fn fetch_cloned_fixed_offset_var<'a, 'tcx>(
808 cx: &LateContext<'a, 'tcx>,
811 ) -> Option<FixedOffsetVar> {
813 if let ExprMethodCall(ref method, _, ref args) = expr.node;
814 if method.name == "clone";
816 if let Some(arg) = args.get(0);
818 return get_fixed_offset_var(cx, arg, var);
822 get_fixed_offset_var(cx, expr, var)
825 fn get_indexed_assignments<'a, 'tcx>(
826 cx: &LateContext<'a, 'tcx>,
829 ) -> Vec<(FixedOffsetVar, FixedOffsetVar)> {
830 fn get_assignment<'a, 'tcx>(
831 cx: &LateContext<'a, 'tcx>,
834 ) -> Option<(FixedOffsetVar, FixedOffsetVar)> {
835 if let Expr_::ExprAssign(ref lhs, ref rhs) = e.node {
836 match (get_fixed_offset_var(cx, lhs, var), fetch_cloned_fixed_offset_var(cx, rhs, var)) {
837 (Some(offset_left), Some(offset_right)) => {
838 // Source and destination must be different
839 if offset_left.var_name == offset_right.var_name {
842 Some((offset_left, offset_right))
852 if let Expr_::ExprBlock(ref b, _) = body.node {
861 .map(|stmt| match stmt.node {
862 Stmt_::StmtDecl(..) => None,
863 Stmt_::StmtExpr(ref e, _node_id) | Stmt_::StmtSemi(ref e, _node_id) => Some(get_assignment(cx, e, var)),
868 .map(|e| Some(get_assignment(cx, &*e, var))),
871 .collect::<Option<Vec<_>>>()
872 .unwrap_or_else(|| vec![])
874 get_assignment(cx, body, var).into_iter().collect()
878 /// Check for for loops that sequentially copy items from one slice-like
879 /// object to another.
880 fn detect_manual_memcpy<'a, 'tcx>(
881 cx: &LateContext<'a, 'tcx>,
887 if let Some(higher::Range {
891 }) = higher::range(cx, arg)
893 // the var must be a single name
894 if let PatKind::Binding(_, canonical_id, _, _) = pat.node {
895 let print_sum = |arg1: &Offset, arg2: &Offset| -> String {
896 match (&arg1.value[..], arg1.negate, &arg2.value[..], arg2.negate) {
897 ("0", _, "0", _) => "".into(),
898 ("0", _, x, false) | (x, false, "0", false) => x.into(),
899 ("0", _, x, true) | (x, false, "0", true) => format!("-{}", x),
900 (x, false, y, false) => format!("({} + {})", x, y),
901 (x, false, y, true) => format!("({} - {})", x, y),
902 (x, true, y, false) => format!("({} - {})", y, x),
903 (x, true, y, true) => format!("-({} + {})", x, y),
907 let print_limit = |end: &Option<&Expr>, offset: Offset, var_name: &str| if let Some(end) = *end {
909 if let ExprMethodCall(ref method, _, ref len_args) = end.node;
910 if method.name == "len";
911 if len_args.len() == 1;
912 if let Some(arg) = len_args.get(0);
913 if snippet(cx, arg.span, "??") == var_name;
915 return if offset.negate {
916 format!("({} - {})", snippet(cx, end.span, "<src>.len()"), offset.value)
923 let end_str = match limits {
924 ast::RangeLimits::Closed => {
925 let end = sugg::Sugg::hir(cx, end, "<count>");
926 format!("{}", end + sugg::ONE)
928 ast::RangeLimits::HalfOpen => format!("{}", snippet(cx, end.span, "..")),
931 print_sum(&Offset::positive(end_str), &offset)
936 // The only statements in the for loops can be indexed assignments from
937 // indexed retrievals.
938 let manual_copies = get_indexed_assignments(cx, body, canonical_id);
940 let big_sugg = manual_copies
942 .map(|(dst_var, src_var)| {
943 let start_str = Offset::positive(snippet_opt(cx, start.span).unwrap_or_else(|| "".into()));
944 let dst_offset = print_sum(&start_str, &dst_var.offset);
945 let dst_limit = print_limit(end, dst_var.offset, &dst_var.var_name);
946 let src_offset = print_sum(&start_str, &src_var.offset);
947 let src_limit = print_limit(end, src_var.offset, &src_var.var_name);
948 let dst = if dst_offset == "" && dst_limit == "" {
951 format!("{}[{}..{}]", dst_var.var_name, dst_offset, dst_limit)
954 format!("{}.clone_from_slice(&{}[{}..{}])", dst, src_var.var_name, src_offset, src_limit)
958 if !big_sugg.is_empty() {
963 "it looks like you're manually copying between slices",
964 "try replacing the loop by",
972 /// Check for looping over a range and then indexing a sequence with it.
973 /// The iteratee must be a range literal.
974 fn check_for_loop_range<'a, 'tcx>(
975 cx: &LateContext<'a, 'tcx>,
981 if let Some(higher::Range {
985 }) = higher::range(cx, arg)
987 // the var must be a single name
988 if let PatKind::Binding(_, canonical_id, ref ident, _) = pat.node {
989 let mut visitor = VarVisitor {
992 indexed_mut: HashSet::new(),
993 indexed_indirectly: HashMap::new(),
994 indexed_directly: HashMap::new(),
995 referenced: HashSet::new(),
997 prefer_mutable: false,
999 walk_expr(&mut visitor, body);
1001 // linting condition: we only indexed one variable, and indexed it directly
1002 if visitor.indexed_indirectly.is_empty() && visitor.indexed_directly.len() == 1 {
1003 let (indexed, indexed_extent) = visitor
1007 .expect("already checked that we have exactly 1 element");
1009 // ensure that the indexed variable was declared before the loop, see #601
1010 if let Some(indexed_extent) = indexed_extent {
1011 let parent_id = cx.tcx.hir.get_parent(expr.id);
1012 let parent_def_id = cx.tcx.hir.local_def_id(parent_id);
1013 let region_scope_tree = cx.tcx.region_scope_tree(parent_def_id);
1014 let pat_extent = region_scope_tree.var_scope(pat.hir_id.local_id);
1015 if region_scope_tree.is_subscope_of(indexed_extent, pat_extent) {
1020 // don't lint if the container that is indexed into is also used without
1022 if visitor.referenced.contains(&indexed) {
1026 let starts_at_zero = is_integer_literal(start, 0);
1028 let skip = if starts_at_zero {
1031 format!(".skip({})", snippet(cx, start.span, ".."))
1034 let take = if let Some(end) = *end {
1035 if is_len_call(end, indexed) {
1039 ast::RangeLimits::Closed => {
1040 let end = sugg::Sugg::hir(cx, end, "<count>");
1041 format!(".take({})", end + sugg::ONE)
1043 ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, end.span, "..")),
1050 let (ref_mut, method) = if visitor.indexed_mut.contains(&indexed) {
1051 ("mut ", "iter_mut")
1056 if visitor.nonindex {
1059 NEEDLESS_RANGE_LOOP,
1061 &format!("the loop variable `{}` is used to index `{}`", ident.node, indexed),
1065 "consider using an iterator".to_string(),
1067 (pat.span, format!("({}, <item>)", ident.node)),
1068 (arg.span, format!("{}.{}().enumerate(){}{}", indexed, method, take, skip)),
1074 let repl = if starts_at_zero && take.is_empty() {
1075 format!("&{}{}", ref_mut, indexed)
1077 format!("{}.{}(){}{}", indexed, method, take, skip)
1082 NEEDLESS_RANGE_LOOP,
1084 &format!("the loop variable `{}` is only used to index `{}`.", ident.node, indexed),
1088 "consider using an iterator".to_string(),
1089 vec![(pat.span, "<item>".to_string()), (arg.span, repl)],
1099 fn is_len_call(expr: &Expr, var: Name) -> bool {
1101 if let ExprMethodCall(ref method, _, ref len_args) = expr.node;
1102 if len_args.len() == 1;
1103 if method.name == "len";
1104 if let ExprPath(QPath::Resolved(_, ref path)) = len_args[0].node;
1105 if path.segments.len() == 1;
1106 if path.segments[0].name == var;
1115 fn check_for_loop_reverse_range<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arg: &'tcx Expr, expr: &'tcx Expr) {
1116 // if this for loop is iterating over a two-sided range...
1117 if let Some(higher::Range {
1121 }) = higher::range(cx, arg)
1123 // ...and both sides are compile-time constant integers...
1124 if let Some((start_idx, _)) = constant(cx, cx.tables, start) {
1125 if let Some((end_idx, _)) = constant(cx, cx.tables, end) {
1126 // ...and the start index is greater than the end index,
1127 // this loop will never run. This is often confusing for developers
1128 // who think that this will iterate from the larger value to the
1130 let ty = cx.tables.expr_ty(start);
1131 let (sup, eq) = match (start_idx, end_idx) {
1133 Constant::Int(start_idx),
1134 Constant::Int(end_idx),
1135 ) => (match ty.sty {
1136 ty::TyInt(ity) => sext(cx.tcx, start_idx, ity) > sext(cx.tcx, end_idx, ity),
1137 ty::TyUint(_) => start_idx > end_idx,
1139 }, start_idx == end_idx),
1140 _ => (false, false),
1144 let start_snippet = snippet(cx, start.span, "_");
1145 let end_snippet = snippet(cx, end.span, "_");
1146 let dots = if limits == ast::RangeLimits::Closed {
1156 "this range is empty so this for loop will never run",
1160 "consider using the following if you are attempting to iterate over this \
1163 "({end}{dots}{start}).rev()",
1166 start = start_snippet
1171 } else if eq && limits != ast::RangeLimits::Closed {
1172 // if they are equal, it's also problematic - this loop
1178 "this range is empty so this for loop will never run",
1186 fn lint_iter_method(cx: &LateContext, args: &[Expr], arg: &Expr, method_name: &str) {
1187 let object = snippet(cx, args[0].span, "_");
1188 let muta = if method_name == "iter_mut" {
1197 "it is more idiomatic to loop over references to containers instead of using explicit \
1199 "to write this more concisely, try",
1200 format!("&{}{}", muta, object),
1204 fn check_for_loop_arg(cx: &LateContext, pat: &Pat, arg: &Expr, expr: &Expr) {
1205 let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
1206 if let ExprMethodCall(ref method, _, ref args) = arg.node {
1207 // just the receiver, no arguments
1208 if args.len() == 1 {
1209 let method_name = &*method.name.as_str();
1210 // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
1211 if method_name == "iter" || method_name == "iter_mut" {
1212 if is_ref_iterable_type(cx, &args[0]) {
1213 lint_iter_method(cx, args, arg, method_name);
1215 } else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
1216 let def_id = cx.tables.type_dependent_defs()[arg.hir_id].def_id();
1217 let substs = cx.tables.node_substs(arg.hir_id);
1218 let method_type = cx.tcx.type_of(def_id).subst(cx.tcx, substs);
1220 let fn_arg_tys = method_type.fn_sig(cx.tcx).inputs();
1221 assert_eq!(fn_arg_tys.skip_binder().len(), 1);
1222 if fn_arg_tys.skip_binder()[0].is_region_ptr() {
1223 match cx.tables.expr_ty(&args[0]).sty {
1224 // If the length is greater than 32 no traits are implemented for array and
1225 // therefore we cannot use `&`.
1226 ty::TypeVariants::TyArray(_, size) if size.assert_usize(cx.tcx).expect("array size") > 32 => (),
1227 _ => lint_iter_method(cx, args, arg, method_name),
1230 let object = snippet(cx, args[0].span, "_");
1233 EXPLICIT_INTO_ITER_LOOP,
1235 "it is more idiomatic to loop over containers instead of using explicit \
1236 iteration methods`",
1237 "to write this more concisely, try",
1241 } else if method_name == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
1246 "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
1247 probably not what you want",
1249 next_loop_linted = true;
1253 if !next_loop_linted {
1254 check_arg_type(cx, pat, arg);
1258 /// Check for `for` loops over `Option`s and `Results`
1259 fn check_arg_type(cx: &LateContext, pat: &Pat, arg: &Expr) {
1260 let ty = cx.tables.expr_ty(arg);
1261 if match_type(cx, ty, &paths::OPTION) {
1264 FOR_LOOP_OVER_OPTION,
1267 "for loop over `{0}`, which is an `Option`. This is more readably written as an \
1268 `if let` statement.",
1269 snippet(cx, arg.span, "_")
1272 "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
1273 snippet(cx, pat.span, "_"),
1274 snippet(cx, arg.span, "_")
1277 } else if match_type(cx, ty, &paths::RESULT) {
1280 FOR_LOOP_OVER_RESULT,
1283 "for loop over `{0}`, which is a `Result`. This is more readably written as an \
1284 `if let` statement.",
1285 snippet(cx, arg.span, "_")
1288 "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
1289 snippet(cx, pat.span, "_"),
1290 snippet(cx, arg.span, "_")
1296 fn check_for_loop_explicit_counter<'a, 'tcx>(
1297 cx: &LateContext<'a, 'tcx>,
1302 // Look for variables that are incremented once per loop iteration.
1303 let mut visitor = IncrementVisitor {
1305 states: HashMap::new(),
1309 walk_expr(&mut visitor, body);
1311 // For each candidate, check the parent block to see if
1312 // it's initialized to zero at the start of the loop.
1313 let map = &cx.tcx.hir;
1314 let parent_scope = map.get_enclosing_scope(expr.id)
1315 .and_then(|id| map.get_enclosing_scope(id));
1316 if let Some(parent_id) = parent_scope {
1317 if let NodeBlock(block) = map.get(parent_id) {
1318 for (id, _) in visitor
1321 .filter(|&(_, v)| *v == VarState::IncrOnce)
1323 let mut visitor2 = InitializeVisitor {
1327 state: VarState::IncrOnce,
1332 walk_block(&mut visitor2, block);
1334 if visitor2.state == VarState::Warn {
1335 if let Some(name) = visitor2.name {
1338 EXPLICIT_COUNTER_LOOP,
1341 "the variable `{0}` is used as a loop counter. Consider using `for ({0}, \
1342 item) in {1}.enumerate()` or similar iterators",
1344 snippet(cx, arg.span, "_")
1354 /// Check for the `FOR_KV_MAP` lint.
1355 fn check_for_loop_over_map_kv<'a, 'tcx>(
1356 cx: &LateContext<'a, 'tcx>,
1362 let pat_span = pat.span;
1364 if let PatKind::Tuple(ref pat, _) = pat.node {
1366 let arg_span = arg.span;
1367 let (new_pat_span, kind, ty, mutbl) = match cx.tables.expr_ty(arg).sty {
1368 ty::TyRef(_, ty, mutbl) => match (&pat[0].node, &pat[1].node) {
1369 (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", ty, mutbl),
1370 (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", ty, MutImmutable),
1375 let mutbl = match mutbl {
1377 MutMutable => "_mut",
1379 let arg = match arg.node {
1380 ExprAddrOf(_, ref expr) => &**expr,
1384 if match_type(cx, ty, &paths::HASHMAP) || match_type(cx, ty, &paths::BTREEMAP) {
1389 &format!("you seem to want to iterate on a map's {}s", kind),
1391 let map = sugg::Sugg::hir(cx, arg, "map");
1394 "use the corresponding method".into(),
1396 (pat_span, snippet(cx, new_pat_span, kind).into_owned()),
1397 (arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)),
1407 struct MutatePairDelegate {
1408 node_id_low: Option<NodeId>,
1409 node_id_high: Option<NodeId>,
1410 span_low: Option<Span>,
1411 span_high: Option<Span>,
1414 impl<'tcx> Delegate<'tcx> for MutatePairDelegate {
1415 fn consume(&mut self, _: NodeId, _: Span, _: &cmt_<'tcx>, _: ConsumeMode) {}
1417 fn matched_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: MatchMode) {}
1419 fn consume_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: ConsumeMode) {}
1421 fn borrow(&mut self, _: NodeId, sp: Span, cmt: &cmt_<'tcx>, _: ty::Region, bk: ty::BorrowKind, _: LoanCause) {
1422 if let ty::BorrowKind::MutBorrow = bk {
1423 if let Categorization::Local(id) = cmt.cat {
1424 if Some(id) == self.node_id_low {
1425 self.span_low = Some(sp)
1427 if Some(id) == self.node_id_high {
1428 self.span_high = Some(sp)
1434 fn mutate(&mut self, _: NodeId, sp: Span, cmt: &cmt_<'tcx>, _: MutateMode) {
1435 if let Categorization::Local(id) = cmt.cat {
1436 if Some(id) == self.node_id_low {
1437 self.span_low = Some(sp)
1439 if Some(id) == self.node_id_high {
1440 self.span_high = Some(sp)
1445 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
1448 impl<'tcx> MutatePairDelegate {
1449 fn mutation_span(&self) -> (Option<Span>, Option<Span>) {
1450 (self.span_low, self.span_high)
1454 fn check_for_mut_range_bound(cx: &LateContext, arg: &Expr, body: &Expr) {
1455 if let Some(higher::Range {
1459 }) = higher::range(cx, arg)
1462 check_for_mutability(cx, start),
1463 check_for_mutability(cx, end),
1465 if mut_ids[0].is_some() || mut_ids[1].is_some() {
1466 let (span_low, span_high) = check_for_mutation(cx, body, &mut_ids);
1467 mut_warn_with_span(cx, span_low);
1468 mut_warn_with_span(cx, span_high);
1473 fn mut_warn_with_span(cx: &LateContext, span: Option<Span>) {
1474 if let Some(sp) = span {
1479 "attempt to mutate range bound within loop; note that the range of the loop is unchanged",
1484 fn check_for_mutability(cx: &LateContext, bound: &Expr) -> Option<NodeId> {
1486 if let ExprPath(ref qpath) = bound.node;
1487 if let QPath::Resolved(None, _) = *qpath;
1489 let def = cx.tables.qpath_def(qpath, bound.hir_id);
1490 if let Def::Local(node_id) = def {
1491 let node_str = cx.tcx.hir.get(node_id);
1493 if let map::Node::NodeBinding(pat) = node_str;
1494 if let PatKind::Binding(bind_ann, _, _, _) = pat.node;
1495 if let BindingAnnotation::Mutable = bind_ann;
1497 return Some(node_id);
1506 fn check_for_mutation(cx: &LateContext, body: &Expr, bound_ids: &[Option<NodeId>]) -> (Option<Span>, Option<Span>) {
1507 let mut delegate = MutatePairDelegate {
1508 node_id_low: bound_ids[0],
1509 node_id_high: bound_ids[1],
1513 let def_id = def_id::DefId::local(body.hir_id.owner);
1514 let region_scope_tree = &cx.tcx.region_scope_tree(def_id);
1515 ExprUseVisitor::new(&mut delegate, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None).walk_expr(body);
1516 delegate.mutation_span()
1519 /// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`.
1520 fn pat_is_wild<'tcx>(pat: &'tcx PatKind, body: &'tcx Expr) -> bool {
1522 PatKind::Wild => true,
1523 PatKind::Binding(_, _, ident, None) if ident.node.as_str().starts_with('_') => {
1524 let mut visitor = UsedVisitor {
1528 walk_expr(&mut visitor, body);
1535 struct UsedVisitor {
1536 var: ast::Name, // var to look for
1537 used: bool, // has the var been used otherwise?
1540 impl<'tcx> Visitor<'tcx> for UsedVisitor {
1541 fn visit_expr(&mut self, expr: &'tcx Expr) {
1542 if match_var(expr, self.var) {
1545 walk_expr(self, expr);
1549 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1550 NestedVisitorMap::None
1554 struct LocalUsedVisitor<'a, 'tcx: 'a> {
1555 cx: &'a LateContext<'a, 'tcx>,
1560 impl<'a, 'tcx: 'a> Visitor<'tcx> for LocalUsedVisitor<'a, 'tcx> {
1561 fn visit_expr(&mut self, expr: &'tcx Expr) {
1562 if same_var(self.cx, expr, self.local) {
1565 walk_expr(self, expr);
1569 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1570 NestedVisitorMap::None
1574 struct VarVisitor<'a, 'tcx: 'a> {
1575 /// context reference
1576 cx: &'a LateContext<'a, 'tcx>,
1577 /// var name to look for as index
1579 /// indexed variables that are used mutably
1580 indexed_mut: HashSet<Name>,
1581 /// indirectly indexed variables (`v[(i + 4) % N]`), the extend is `None` for global
1582 indexed_indirectly: HashMap<Name, Option<region::Scope>>,
1583 /// subset of `indexed` of vars that are indexed directly: `v[i]`
1584 /// this will not contain cases like `v[calc_index(i)]` or `v[(i + 4) % N]`
1585 indexed_directly: HashMap<Name, Option<region::Scope>>,
1586 /// Any names that are used outside an index operation.
1587 /// Used to detect things like `&mut vec` used together with `vec[i]`
1588 referenced: HashSet<Name>,
1589 /// has the loop variable been used in expressions other than the index of
1592 /// Whether we are inside the `$` in `&mut $` or `$ = foo` or `$.bar`, where bar
1593 /// takes `&mut self`
1594 prefer_mutable: bool,
1597 impl<'a, 'tcx> VarVisitor<'a, 'tcx> {
1598 fn check(&mut self, idx: &'tcx Expr, seqexpr: &'tcx Expr, expr: &'tcx Expr) -> bool {
1600 // the indexed container is referenced by a name
1601 if let ExprPath(ref seqpath) = seqexpr.node;
1602 if let QPath::Resolved(None, ref seqvar) = *seqpath;
1603 if seqvar.segments.len() == 1;
1605 let index_used_directly = same_var(self.cx, idx, self.var);
1606 let indexed_indirectly = {
1607 let mut used_visitor = LocalUsedVisitor {
1612 walk_expr(&mut used_visitor, idx);
1616 if indexed_indirectly || index_used_directly {
1617 if self.prefer_mutable {
1618 self.indexed_mut.insert(seqvar.segments[0].name);
1620 let def = self.cx.tables.qpath_def(seqpath, seqexpr.hir_id);
1622 Def::Local(node_id) | Def::Upvar(node_id, ..) => {
1623 let hir_id = self.cx.tcx.hir.node_to_hir_id(node_id);
1625 let parent_id = self.cx.tcx.hir.get_parent(expr.id);
1626 let parent_def_id = self.cx.tcx.hir.local_def_id(parent_id);
1627 let extent = self.cx.tcx.region_scope_tree(parent_def_id).var_scope(hir_id.local_id);
1628 if indexed_indirectly {
1629 self.indexed_indirectly.insert(seqvar.segments[0].name, Some(extent));
1631 if index_used_directly {
1632 self.indexed_directly.insert(seqvar.segments[0].name, Some(extent));
1634 return false; // no need to walk further *on the variable*
1636 Def::Static(..) | Def::Const(..) => {
1637 if indexed_indirectly {
1638 self.indexed_indirectly.insert(seqvar.segments[0].name, None);
1640 if index_used_directly {
1641 self.indexed_directly.insert(seqvar.segments[0].name, None);
1643 return false; // no need to walk further *on the variable*
1654 impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
1655 fn visit_expr(&mut self, expr: &'tcx Expr) {
1658 if let ExprMethodCall(ref meth, _, ref args) = expr.node;
1659 if (meth.name == "index" && match_trait_method(self.cx, expr, &paths::INDEX))
1660 || (meth.name == "index_mut" && match_trait_method(self.cx, expr, &paths::INDEX_MUT));
1661 if !self.check(&args[1], &args[0], expr);
1667 if let ExprIndex(ref seqexpr, ref idx) = expr.node;
1668 if !self.check(idx, seqexpr, expr);
1673 // directly using a variable
1674 if let ExprPath(ref qpath) = expr.node;
1675 if let QPath::Resolved(None, ref path) = *qpath;
1676 if path.segments.len() == 1;
1677 if let Def::Local(local_id) = self.cx.tables.qpath_def(qpath, expr.hir_id);
1679 if local_id == self.var {
1680 // we are not indexing anything, record that
1681 self.nonindex = true;
1683 // not the correct variable, but still a variable
1684 self.referenced.insert(path.segments[0].name);
1688 let old = self.prefer_mutable;
1690 ExprAssignOp(_, ref lhs, ref rhs) |
1691 ExprAssign(ref lhs, ref rhs) => {
1692 self.prefer_mutable = true;
1693 self.visit_expr(lhs);
1694 self.prefer_mutable = false;
1695 self.visit_expr(rhs);
1697 ExprAddrOf(mutbl, ref expr) => {
1698 if mutbl == MutMutable {
1699 self.prefer_mutable = true;
1701 self.visit_expr(expr);
1703 ExprCall(ref f, ref args) => {
1706 let ty = self.cx.tables.expr_ty_adjusted(expr);
1707 self.prefer_mutable = false;
1708 if let ty::TyRef(_, _, mutbl) = ty.sty {
1709 if mutbl == MutMutable {
1710 self.prefer_mutable = true;
1713 self.visit_expr(expr);
1716 ExprMethodCall(_, _, ref args) => {
1717 let def_id = self.cx.tables.type_dependent_defs()[expr.hir_id].def_id();
1718 for (ty, expr) in self.cx.tcx.fn_sig(def_id).inputs().skip_binder().iter().zip(args) {
1719 self.prefer_mutable = false;
1720 if let ty::TyRef(_, _, mutbl) = ty.sty {
1721 if mutbl == MutMutable {
1722 self.prefer_mutable = true;
1725 self.visit_expr(expr);
1728 _ => walk_expr(self, expr),
1730 self.prefer_mutable = old;
1732 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1733 NestedVisitorMap::None
1737 fn is_iterator_used_after_while_let<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, iter_expr: &'tcx Expr) -> bool {
1738 let def_id = match var_def_id(cx, iter_expr) {
1740 None => return false,
1742 let mut visitor = VarUsedAfterLoopVisitor {
1745 iter_expr_id: iter_expr.id,
1746 past_while_let: false,
1747 var_used_after_while_let: false,
1749 if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
1750 walk_block(&mut visitor, enclosing_block);
1752 visitor.var_used_after_while_let
1755 struct VarUsedAfterLoopVisitor<'a, 'tcx: 'a> {
1756 cx: &'a LateContext<'a, 'tcx>,
1758 iter_expr_id: NodeId,
1759 past_while_let: bool,
1760 var_used_after_while_let: bool,
1763 impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
1764 fn visit_expr(&mut self, expr: &'tcx Expr) {
1765 if self.past_while_let {
1766 if Some(self.def_id) == var_def_id(self.cx, expr) {
1767 self.var_used_after_while_let = true;
1769 } else if self.iter_expr_id == expr.id {
1770 self.past_while_let = true;
1772 walk_expr(self, expr);
1774 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1775 NestedVisitorMap::None
1780 /// Return true if the type of expr is one that provides `IntoIterator` impls
1781 /// for `&T` and `&mut T`, such as `Vec`.
1782 #[cfg_attr(rustfmt, rustfmt_skip)]
1783 fn is_ref_iterable_type(cx: &LateContext, e: &Expr) -> bool {
1784 // no walk_ptrs_ty: calling iter() on a reference can make sense because it
1785 // will allow further borrows afterwards
1786 let ty = cx.tables.expr_ty(e);
1787 is_iterable_array(ty, cx) ||
1788 match_type(cx, ty, &paths::VEC) ||
1789 match_type(cx, ty, &paths::LINKED_LIST) ||
1790 match_type(cx, ty, &paths::HASHMAP) ||
1791 match_type(cx, ty, &paths::HASHSET) ||
1792 match_type(cx, ty, &paths::VEC_DEQUE) ||
1793 match_type(cx, ty, &paths::BINARY_HEAP) ||
1794 match_type(cx, ty, &paths::BTREEMAP) ||
1795 match_type(cx, ty, &paths::BTREESET)
1798 fn is_iterable_array(ty: Ty, cx: &LateContext) -> bool {
1799 // IntoIterator is currently only implemented for array sizes <= 32 in rustc
1801 ty::TyArray(_, n) => (0..=32).contains(&n.assert_usize(cx.tcx).expect("array length")),
1806 /// If a block begins with a statement (possibly a `let` binding) and has an
1807 /// expression, return it.
1808 fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
1809 if block.stmts.is_empty() {
1812 if let StmtDecl(ref decl, _) = block.stmts[0].node {
1813 if let DeclLocal(ref local) = decl.node {
1814 if let Some(ref expr) = local.init {
1827 /// If a block begins with an expression (with or without semicolon), return it.
1828 fn extract_first_expr(block: &Block) -> Option<&Expr> {
1830 Some(ref expr) if block.stmts.is_empty() => Some(expr),
1831 None if !block.stmts.is_empty() => match block.stmts[0].node {
1832 StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => Some(expr),
1833 StmtDecl(..) => None,
1839 /// Return true if expr contains a single break expr without destination label
1841 /// passed expression. The expression may be within a block.
1842 fn is_simple_break_expr(expr: &Expr) -> bool {
1844 ExprBreak(dest, ref passed_expr) if dest.label.is_none() && passed_expr.is_none() => true,
1845 ExprBlock(ref b, _) => match extract_first_expr(b) {
1846 Some(subexpr) => is_simple_break_expr(subexpr),
1853 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
1854 // incremented exactly once in the loop body, and initialized to zero
1855 // at the start of the loop.
1856 #[derive(PartialEq)]
1858 Initial, // Not examined yet
1859 IncrOnce, // Incremented exactly once, may be a loop counter
1860 Declared, // Declared but not (yet) initialized to zero
1865 /// Scan a for loop for variables that are incremented exactly once.
1866 struct IncrementVisitor<'a, 'tcx: 'a> {
1867 cx: &'a LateContext<'a, 'tcx>, // context reference
1868 states: HashMap<NodeId, VarState>, // incremented variables
1869 depth: u32, // depth of conditional expressions
1873 impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
1874 fn visit_expr(&mut self, expr: &'tcx Expr) {
1879 // If node is a variable
1880 if let Some(def_id) = var_def_id(self.cx, expr) {
1881 if let Some(parent) = get_parent_expr(self.cx, expr) {
1882 let state = self.states.entry(def_id).or_insert(VarState::Initial);
1885 ExprAssignOp(op, ref lhs, ref rhs) => {
1886 if lhs.id == expr.id {
1887 if op.node == BiAdd && is_integer_literal(rhs, 1) {
1888 *state = match *state {
1889 VarState::Initial if self.depth == 0 => VarState::IncrOnce,
1890 _ => VarState::DontWarn,
1893 // Assigned some other value
1894 *state = VarState::DontWarn;
1898 ExprAssign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
1899 ExprAddrOf(mutability, _) if mutability == MutMutable => *state = VarState::DontWarn,
1903 } else if is_loop(expr) {
1904 self.states.clear();
1907 } else if is_conditional(expr) {
1909 walk_expr(self, expr);
1913 walk_expr(self, expr);
1915 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1916 NestedVisitorMap::None
1920 /// Check whether a variable is initialized to zero at the start of a loop.
1921 struct InitializeVisitor<'a, 'tcx: 'a> {
1922 cx: &'a LateContext<'a, 'tcx>, // context reference
1923 end_expr: &'tcx Expr, // the for loop. Stop scanning here.
1927 depth: u32, // depth of conditional expressions
1931 impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
1932 fn visit_decl(&mut self, decl: &'tcx Decl) {
1933 // Look for declarations of the variable
1934 if let DeclLocal(ref local) = decl.node {
1935 if local.pat.id == self.var_id {
1936 if let PatKind::Binding(_, _, ref ident, _) = local.pat.node {
1937 self.name = Some(ident.node);
1939 self.state = if let Some(ref init) = local.init {
1940 if is_integer_literal(init, 0) {
1951 walk_decl(self, decl);
1954 fn visit_expr(&mut self, expr: &'tcx Expr) {
1955 if self.state == VarState::DontWarn {
1958 if expr == self.end_expr {
1959 self.past_loop = true;
1962 // No need to visit expressions before the variable is
1964 if self.state == VarState::IncrOnce {
1968 // If node is the desired variable, see how it's used
1969 if var_def_id(self.cx, expr) == Some(self.var_id) {
1970 if let Some(parent) = get_parent_expr(self.cx, expr) {
1972 ExprAssignOp(_, ref lhs, _) if lhs.id == expr.id => {
1973 self.state = VarState::DontWarn;
1975 ExprAssign(ref lhs, ref rhs) if lhs.id == expr.id => {
1976 self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
1982 ExprAddrOf(mutability, _) if mutability == MutMutable => self.state = VarState::DontWarn,
1988 self.state = VarState::DontWarn;
1991 } else if !self.past_loop && is_loop(expr) {
1992 self.state = VarState::DontWarn;
1994 } else if is_conditional(expr) {
1996 walk_expr(self, expr);
2000 walk_expr(self, expr);
2002 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2003 NestedVisitorMap::None
2007 fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
2008 if let ExprPath(ref qpath) = expr.node {
2009 let path_res = cx.tables.qpath_def(qpath, expr.hir_id);
2010 if let Def::Local(node_id) = path_res {
2011 return Some(node_id);
2017 fn is_loop(expr: &Expr) -> bool {
2019 ExprLoop(..) | ExprWhile(..) => true,
2024 fn is_conditional(expr: &Expr) -> bool {
2026 ExprIf(..) | ExprMatch(..) => true,
2031 fn is_nested(cx: &LateContext, match_expr: &Expr, iter_expr: &Expr) -> bool {
2033 if let Some(loop_block) = get_enclosing_block(cx, match_expr.id);
2034 if let Some(map::Node::NodeExpr(loop_expr)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(loop_block.id));
2036 return is_loop_nested(cx, loop_expr, iter_expr)
2042 fn is_loop_nested(cx: &LateContext, loop_expr: &Expr, iter_expr: &Expr) -> bool {
2043 let mut id = loop_expr.id;
2044 let iter_name = if let Some(name) = path_name(iter_expr) {
2050 let parent = cx.tcx.hir.get_parent_node(id);
2054 match cx.tcx.hir.find(parent) {
2055 Some(NodeExpr(expr)) => match expr.node {
2056 ExprLoop(..) | ExprWhile(..) => {
2061 Some(NodeBlock(block)) => {
2062 let mut block_visitor = LoopNestVisitor {
2064 iterator: iter_name,
2067 walk_block(&mut block_visitor, block);
2068 if block_visitor.nesting == RuledOut {
2072 Some(NodeStmt(_)) => (),
2081 #[derive(PartialEq, Eq)]
2083 Unknown, // no nesting detected yet
2084 RuledOut, // the iterator is initialized or assigned within scope
2085 LookFurther, // no nesting detected, no further walk required
2088 use self::Nesting::{LookFurther, RuledOut, Unknown};
2090 struct LoopNestVisitor {
2096 impl<'tcx> Visitor<'tcx> for LoopNestVisitor {
2097 fn visit_stmt(&mut self, stmt: &'tcx Stmt) {
2098 if stmt.node.id() == self.id {
2099 self.nesting = LookFurther;
2100 } else if self.nesting == Unknown {
2101 walk_stmt(self, stmt);
2105 fn visit_expr(&mut self, expr: &'tcx Expr) {
2106 if self.nesting != Unknown {
2109 if expr.id == self.id {
2110 self.nesting = LookFurther;
2114 ExprAssign(ref path, _) | ExprAssignOp(_, ref path, _) => if match_var(path, self.iterator) {
2115 self.nesting = RuledOut;
2117 _ => walk_expr(self, expr),
2121 fn visit_pat(&mut self, pat: &'tcx Pat) {
2122 if self.nesting != Unknown {
2125 if let PatKind::Binding(_, _, span_name, _) = pat.node {
2126 if self.iterator == span_name.node {
2127 self.nesting = RuledOut;
2134 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2135 NestedVisitorMap::None
2139 fn path_name(e: &Expr) -> Option<Name> {
2140 if let ExprPath(QPath::Resolved(_, ref path)) = e.node {
2141 let segments = &path.segments;
2142 if segments.len() == 1 {
2143 return Some(segments[0].name);
2149 fn check_infinite_loop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, cond: &'tcx Expr, expr: &'tcx Expr) {
2150 if constant(cx, cx.tables, cond).is_some() {
2151 // A pure constant condition (e.g. while false) is not linted.
2155 let mut var_visitor = VarCollectorVisitor {
2157 ids: HashSet::new(),
2158 def_ids: HashMap::new(),
2161 var_visitor.visit_expr(cond);
2162 if var_visitor.skip {
2165 let used_in_condition = &var_visitor.ids;
2166 let no_cond_variable_mutated = if let Some(used_mutably) = mutated_variables(expr, cx) {
2167 used_in_condition.is_disjoint(&used_mutably)
2171 let mutable_static_in_cond = var_visitor.def_ids.iter().any(|(_, v)| *v);
2172 if no_cond_variable_mutated && !mutable_static_in_cond {
2175 WHILE_IMMUTABLE_CONDITION,
2177 "Variable in the condition are not mutated in the loop body. This either leads to an infinite or to a never running loop.",
2182 /// Collects the set of variables in an expression
2183 /// Stops analysis if a function call is found
2184 /// Note: In some cases such as `self`, there are no mutable annotation,
2185 /// All variables definition IDs are collected
2186 struct VarCollectorVisitor<'a, 'tcx: 'a> {
2187 cx: &'a LateContext<'a, 'tcx>,
2188 ids: HashSet<NodeId>,
2189 def_ids: HashMap<def_id::DefId, bool>,
2193 impl<'a, 'tcx> VarCollectorVisitor<'a, 'tcx> {
2194 fn insert_def_id(&mut self, ex: &'tcx Expr) {
2196 if let ExprPath(ref qpath) = ex.node;
2197 if let QPath::Resolved(None, _) = *qpath;
2198 let def = self.cx.tables.qpath_def(qpath, ex.hir_id);
2201 Def::Local(node_id) | Def::Upvar(node_id, ..) => {
2202 self.ids.insert(node_id);
2204 Def::Static(def_id, mutable) => {
2205 self.def_ids.insert(def_id, mutable);
2214 impl<'a, 'tcx> Visitor<'tcx> for VarCollectorVisitor<'a, 'tcx> {
2215 fn visit_expr(&mut self, ex: &'tcx Expr) {
2217 ExprPath(_) => self.insert_def_id(ex),
2218 // If there is any fuction/method call… we just stop analysis
2219 ExprCall(..) | ExprMethodCall(..) => self.skip = true,
2221 _ => walk_expr(self, ex),
2225 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2226 NestedVisitorMap::None