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::{declare_lint, lint_array};
10 use if_chain::if_chain;
11 use rustc::middle::region;
12 // use rustc::middle::region::CodeExtent;
13 use rustc::middle::expr_use_visitor::*;
14 use rustc::middle::mem_categorization::Categorization;
15 use rustc::middle::mem_categorization::cmt_;
16 use rustc::ty::{self, Ty};
17 use rustc::ty::subst::Subst;
18 use std::collections::{HashMap, HashSet};
19 use std::iter::{once, Iterator};
21 use syntax::codemap::Span;
22 use crate::utils::{sugg, sext};
23 use crate::utils::usage::mutated_variables;
24 use crate::consts::{constant, Constant};
26 use crate::utils::{get_enclosing_block, get_parent_expr, higher, is_integer_literal, is_refutable,
27 last_path_segment, match_trait_method, match_type, match_var, multispan_sugg, snippet, snippet_opt,
28 span_help_and_lint, span_lint, span_lint_and_sugg, span_lint_and_then, SpanlessEq};
29 use crate::utils::paths;
31 /// **What it does:** Checks for for-loops that manually copy items between
32 /// slices that could be optimized by having a memcpy.
34 /// **Why is this bad?** It is not as fast as a memcpy.
36 /// **Known problems:** None.
40 /// for i in 0..src.len() {
41 /// dst[i + 64] = src[i];
44 declare_clippy_lint! {
47 "manually copying items between slices"
50 /// **What it does:** Checks for looping over the range of `0..len` of some
51 /// collection just to get the values by index.
53 /// **Why is this bad?** Just iterating the collection itself makes the intent
54 /// more clear and is probably faster.
56 /// **Known problems:** None.
60 /// for i in 0..vec.len() {
61 /// println!("{}", vec[i]);
64 declare_clippy_lint! {
65 pub NEEDLESS_RANGE_LOOP,
67 "for-looping over a range of indices where an iterator over items would do"
70 /// **What it does:** Checks for loops on `x.iter()` where `&x` will do, and
71 /// suggests the latter.
73 /// **Why is this bad?** Readability.
75 /// **Known problems:** False negatives. We currently only warn on some known
80 /// // with `y` a `Vec` or slice:
81 /// for x in y.iter() { .. }
83 declare_clippy_lint! {
84 pub EXPLICIT_ITER_LOOP,
86 "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
89 /// **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and
90 /// suggests the latter.
92 /// **Why is this bad?** Readability.
94 /// **Known problems:** None
98 /// // with `y` a `Vec` or slice:
99 /// for x in y.into_iter() { .. }
101 declare_clippy_lint! {
102 pub EXPLICIT_INTO_ITER_LOOP,
104 "for-looping over `_.into_iter()` when `_` would do"
107 /// **What it does:** Checks for loops on `x.next()`.
109 /// **Why is this bad?** `next()` returns either `Some(value)` if there was a
110 /// value, or `None` otherwise. The insidious thing is that `Option<_>`
111 /// implements `IntoIterator`, so that possibly one value will be iterated,
112 /// leading to some hard to find bugs. No one will want to write such code
113 /// [except to win an Underhanded Rust
114 /// Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
116 /// **Known problems:** None.
120 /// for x in y.next() { .. }
122 declare_clippy_lint! {
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 { .. }
144 declare_clippy_lint! {
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 { .. }
166 declare_clippy_lint! {
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
194 declare_clippy_lint! {
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<_>>();
212 declare_clippy_lint! {
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 `-`
235 declare_clippy_lint! {
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]); }
255 declare_clippy_lint! {
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.
273 declare_clippy_lint! {
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() { .. }
290 declare_clippy_lint! {
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() { .. }
314 declare_clippy_lint! {
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; }
332 declare_clippy_lint! {
335 "any loop that will always `break` or `return`"
338 /// **What it does:** Checks for loops which have a range bound that is a mutable variable
340 /// **Why is this bad?** One might think that modifying the mutable variable changes the loop bounds
342 /// **Known problems:** None
346 /// let mut foo = 42;
347 /// for i in 0..foo {
349 /// println!("{}", i); // prints numbers from 0 to 42, not 0 to 21
352 declare_clippy_lint! {
355 "for loop over a range where one of the bounds is a mutable variable"
358 /// **What it does:** Checks whether variables used within while loop condition
359 /// can be (and are) mutated in the body.
361 /// **Why is this bad?** If the condition is unchanged, entering the body of the loop
362 /// will lead to an infinite loop.
364 /// **Known problems:** If the `while`-loop is in a closure, the check for mutation of the
365 /// condition variables in the body can cause false negatives. For example when only `Upvar` `a` is
366 /// in the condition and only `Upvar` `b` gets mutated in the body, the lint will not trigger.
372 /// println!("let me loop forever!");
375 declare_clippy_lint! {
376 pub WHILE_IMMUTABLE_CONDITION,
378 "variables used within while expression are not mutated in the body"
381 #[derive(Copy, Clone)]
384 impl LintPass for Pass {
385 fn get_lints(&self) -> LintArray {
390 EXPLICIT_INTO_ITER_LOOP,
392 FOR_LOOP_OVER_RESULT,
393 FOR_LOOP_OVER_OPTION,
397 EXPLICIT_COUNTER_LOOP,
399 WHILE_LET_ON_ITERATOR,
403 WHILE_IMMUTABLE_CONDITION,
408 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
409 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
410 if let Some((pat, arg, body)) = higher::for_loop(expr) {
411 check_for_loop(cx, pat, arg, body, expr);
414 // check for never_loop
416 ExprKind::While(_, ref block, _) | ExprKind::Loop(ref block, _, _) => {
417 match never_loop_block(block, expr.id) {
418 NeverLoopResult::AlwaysBreak =>
419 span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops"),
420 NeverLoopResult::MayContinueMainLoop | NeverLoopResult::Otherwise => (),
426 // check for `loop { if let {} else break }` that could be `while let`
427 // (also matches an explicit "match" instead of "if let")
428 // (even if the "match" or "if let" is used for declaration)
429 if let ExprKind::Loop(ref block, _, LoopSource::Loop) = expr.node {
430 // also check for empty `loop {}` statements
431 if block.stmts.is_empty() && block.expr.is_none() {
436 "empty `loop {}` detected. You may want to either use `panic!()` or add \
437 `std::thread::sleep(..);` to the loop body.",
441 // extract the expression from the first statement (if any) in a block
442 let inner_stmt_expr = extract_expr_from_first_stmt(block);
443 // or extract the first expression (if any) from the block
444 if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
445 if let ExprKind::Match(ref matchexpr, ref arms, ref source) = inner.node {
446 // ensure "if let" compatible match structure
448 MatchSource::Normal | MatchSource::IfLetDesugar { .. } => {
449 if arms.len() == 2 && arms[0].pats.len() == 1 && arms[0].guard.is_none()
450 && arms[1].pats.len() == 1 && arms[1].guard.is_none()
451 && is_simple_break_expr(&arms[1].body)
453 if in_external_macro(cx.sess(), expr.span) {
457 // NOTE: we used to make build a body here instead of using
458 // ellipsis, this was removed because:
459 // 1) it was ugly with big bodies;
460 // 2) it was not indented properly;
461 // 3) it wasn’t very smart (see #675).
466 "this loop could be written as a `while let` loop",
469 "while let {} = {} {{ .. }}",
470 snippet(cx, arms[0].pats[0].span, ".."),
471 snippet(cx, matchexpr.span, "..")
481 if let ExprKind::Match(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
482 let pat = &arms[0].pats[0].node;
484 &PatKind::TupleStruct(ref qpath, ref pat_args, _),
485 &ExprKind::MethodCall(ref method_path, _, ref method_args),
486 ) = (pat, &match_expr.node)
488 let iter_expr = &method_args[0];
489 let lhs_constructor = last_path_segment(qpath);
490 if method_path.ident.name == "next" && match_trait_method(cx, match_expr, &paths::ITERATOR)
491 && lhs_constructor.ident.name == "Some" && (
493 || !is_refutable(cx, &pat_args[0])
494 && !is_iterator_used_after_while_let(cx, iter_expr)
495 && !is_nested(cx, expr, &method_args[0]))
497 let iterator = snippet(cx, method_args[0].span, "_");
498 let loop_var = if pat_args.is_empty() {
501 snippet(cx, pat_args[0].span, "_").into_owned()
505 WHILE_LET_ON_ITERATOR,
507 "this loop could be written as a `for` loop",
509 format!("for {} in {} {{ .. }}", loop_var, iterator),
515 // check for while loops which conditions never change
516 if let ExprKind::While(ref cond, _, _) = expr.node {
517 check_infinite_loop(cx, cond, expr);
521 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
522 if let StmtKind::Semi(ref expr, _) = stmt.node {
523 if let ExprKind::MethodCall(ref method, _, ref args) = expr.node {
524 if args.len() == 1 && method.ident.name == "collect" && match_trait_method(cx, expr, &paths::ITERATOR) {
529 "you are collect()ing an iterator and throwing away the result. \
530 Consider using an explicit for loop to exhaust the iterator",
538 enum NeverLoopResult {
539 // A break/return always get triggered but not necessarily for the main loop.
541 // A continue may occur for the main loop.
546 fn absorb_break(arg: &NeverLoopResult) -> NeverLoopResult {
548 NeverLoopResult::AlwaysBreak |
549 NeverLoopResult::Otherwise => NeverLoopResult::Otherwise,
550 NeverLoopResult::MayContinueMainLoop => NeverLoopResult::MayContinueMainLoop,
554 // Combine two results for parts that are called in order.
555 fn combine_seq(first: NeverLoopResult, second: NeverLoopResult) -> NeverLoopResult {
557 NeverLoopResult::AlwaysBreak | NeverLoopResult::MayContinueMainLoop => first,
558 NeverLoopResult::Otherwise => second,
562 // Combine two results where both parts are called but not necessarily in order.
563 fn combine_both(left: NeverLoopResult, right: NeverLoopResult) -> NeverLoopResult {
564 match (left, right) {
565 (NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) =>
566 NeverLoopResult::MayContinueMainLoop,
567 (NeverLoopResult::AlwaysBreak, _) | (_, NeverLoopResult::AlwaysBreak) =>
568 NeverLoopResult::AlwaysBreak,
569 (NeverLoopResult::Otherwise, NeverLoopResult::Otherwise) =>
570 NeverLoopResult::Otherwise,
574 // Combine two results where only one of the part may have been executed.
575 fn combine_branches(b1: NeverLoopResult, b2: NeverLoopResult) -> NeverLoopResult {
577 (NeverLoopResult::AlwaysBreak, NeverLoopResult::AlwaysBreak) =>
578 NeverLoopResult::AlwaysBreak,
579 (NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) =>
580 NeverLoopResult::MayContinueMainLoop,
581 (NeverLoopResult::Otherwise, _) | (_, NeverLoopResult::Otherwise) =>
582 NeverLoopResult::Otherwise,
586 fn never_loop_block(block: &Block, main_loop_id: NodeId) -> NeverLoopResult {
587 let stmts = block.stmts.iter().map(stmt_to_expr);
588 let expr = once(block.expr.as_ref().map(|p| &**p));
589 let mut iter = stmts.chain(expr).filter_map(|e| e);
590 never_loop_expr_seq(&mut iter, main_loop_id)
593 fn stmt_to_expr(stmt: &Stmt) -> Option<&Expr> {
595 StmtKind::Semi(ref e, ..) | StmtKind::Expr(ref e, ..) => Some(e),
596 StmtKind::Decl(ref d, ..) => decl_to_expr(d),
600 fn decl_to_expr(decl: &Decl) -> Option<&Expr> {
602 DeclKind::Local(ref local) => local.init.as_ref().map(|p| &**p),
607 fn never_loop_expr(expr: &Expr, main_loop_id: NodeId) -> NeverLoopResult {
609 ExprKind::Box(ref e) |
610 ExprKind::Unary(_, ref e) |
611 ExprKind::Cast(ref e, _) |
612 ExprKind::Type(ref e, _) |
613 ExprKind::Field(ref e, _) |
614 ExprKind::AddrOf(_, ref e) |
615 ExprKind::Struct(_, _, Some(ref e)) |
616 ExprKind::Repeat(ref e, _) => never_loop_expr(e, main_loop_id),
617 ExprKind::Array(ref es) | ExprKind::MethodCall(_, _, ref es) | ExprKind::Tup(ref es) => {
618 never_loop_expr_all(&mut es.iter(), main_loop_id)
620 ExprKind::Call(ref e, ref es) => never_loop_expr_all(&mut once(&**e).chain(es.iter()), main_loop_id),
621 ExprKind::Binary(_, ref e1, ref e2) |
622 ExprKind::Assign(ref e1, ref e2) |
623 ExprKind::AssignOp(_, ref e1, ref e2) |
624 ExprKind::Index(ref e1, ref e2) => never_loop_expr_all(&mut [&**e1, &**e2].iter().cloned(), main_loop_id),
625 ExprKind::If(ref e, ref e2, ref e3) => {
626 let e1 = never_loop_expr(e, main_loop_id);
627 let e2 = never_loop_expr(e2, main_loop_id);
628 let e3 = e3.as_ref().map_or(NeverLoopResult::Otherwise, |e| never_loop_expr(e, main_loop_id));
629 combine_seq(e1, combine_branches(e2, e3))
631 ExprKind::Loop(ref b, _, _) => {
632 // Break can come from the inner loop so remove them.
633 absorb_break(&never_loop_block(b, main_loop_id))
635 ExprKind::While(ref e, ref b, _) => {
636 let e = never_loop_expr(e, main_loop_id);
637 let result = never_loop_block(b, main_loop_id);
638 // Break can come from the inner loop so remove them.
639 combine_seq(e, absorb_break(&result))
641 ExprKind::Match(ref e, ref arms, _) => {
642 let e = never_loop_expr(e, main_loop_id);
646 let arms = never_loop_expr_branch(&mut arms.iter().map(|a| &*a.body), main_loop_id);
650 ExprKind::Block(ref b, _) => never_loop_block(b, main_loop_id),
651 ExprKind::Continue(d) => {
653 .expect("target id can only be missing in the presence of compilation errors");
654 if id == main_loop_id {
655 NeverLoopResult::MayContinueMainLoop
657 NeverLoopResult::AlwaysBreak
660 ExprKind::Break(_, _) => {
661 NeverLoopResult::AlwaysBreak
663 ExprKind::Ret(ref e) => {
664 if let Some(ref e) = *e {
665 combine_seq(never_loop_expr(e, main_loop_id), NeverLoopResult::AlwaysBreak)
667 NeverLoopResult::AlwaysBreak
670 ExprKind::Struct(_, _, None) |
672 ExprKind::Closure(_, _, _, _, _) |
673 ExprKind::InlineAsm(_, _, _) |
675 ExprKind::Lit(_) => NeverLoopResult::Otherwise,
679 fn never_loop_expr_seq<'a, T: Iterator<Item=&'a Expr>>(es: &mut T, main_loop_id: NodeId) -> NeverLoopResult {
680 es.map(|e| never_loop_expr(e, main_loop_id))
681 .fold(NeverLoopResult::Otherwise, combine_seq)
684 fn never_loop_expr_all<'a, T: Iterator<Item=&'a Expr>>(es: &mut T, main_loop_id: NodeId) -> NeverLoopResult {
685 es.map(|e| never_loop_expr(e, main_loop_id))
686 .fold(NeverLoopResult::Otherwise, combine_both)
689 fn never_loop_expr_branch<'a, T: Iterator<Item=&'a Expr>>(e: &mut T, main_loop_id: NodeId) -> NeverLoopResult {
690 e.map(|e| never_loop_expr(e, main_loop_id))
691 .fold(NeverLoopResult::AlwaysBreak, combine_branches)
694 fn check_for_loop<'a, 'tcx>(
695 cx: &LateContext<'a, 'tcx>,
701 check_for_loop_range(cx, pat, arg, body, expr);
702 check_for_loop_reverse_range(cx, arg, expr);
703 check_for_loop_arg(cx, pat, arg, expr);
704 check_for_loop_explicit_counter(cx, arg, body, expr);
705 check_for_loop_over_map_kv(cx, pat, arg, body, expr);
706 check_for_mut_range_bound(cx, arg, body);
707 detect_manual_memcpy(cx, pat, arg, body, expr);
710 fn same_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr, var: ast::NodeId) -> bool {
712 if let ExprKind::Path(ref qpath) = expr.node;
713 if let QPath::Resolved(None, ref path) = *qpath;
714 if path.segments.len() == 1;
715 if let Def::Local(local_id) = cx.tables.qpath_def(qpath, expr.hir_id);
732 fn negative(s: String) -> Self {
739 fn positive(s: String) -> Self {
747 struct FixedOffsetVar {
752 fn is_slice_like<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'_>) -> bool {
753 let is_slice = match ty.sty {
754 ty::TyRef(_, subty, _) => is_slice_like(cx, subty),
755 ty::TySlice(..) | ty::TyArray(..) => true,
759 is_slice || match_type(cx, ty, &paths::VEC) || match_type(cx, ty, &paths::VEC_DEQUE)
762 fn get_fixed_offset_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr, var: ast::NodeId) -> Option<FixedOffsetVar> {
763 fn extract_offset<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &Expr, var: ast::NodeId) -> Option<String> {
765 ExprKind::Lit(ref l) => match l.node {
766 ast::LitKind::Int(x, _ty) => Some(x.to_string()),
769 ExprKind::Path(..) if !same_var(cx, e, var) => Some(snippet_opt(cx, e.span).unwrap_or_else(|| "??".into())),
774 if let ExprKind::Index(ref seqexpr, ref idx) = expr.node {
775 let ty = cx.tables.expr_ty(seqexpr);
776 if !is_slice_like(cx, ty) {
780 let offset = match idx.node {
781 ExprKind::Binary(op, ref lhs, ref rhs) => match op.node {
783 let offset_opt = if same_var(cx, lhs, var) {
784 extract_offset(cx, rhs, var)
785 } else if same_var(cx, rhs, var) {
786 extract_offset(cx, lhs, var)
791 offset_opt.map(Offset::positive)
793 BinOpKind::Sub if same_var(cx, lhs, var) => extract_offset(cx, rhs, var).map(Offset::negative),
796 ExprKind::Path(..) => if same_var(cx, idx, var) {
797 Some(Offset::positive("0".into()))
806 var_name: snippet_opt(cx, seqexpr.span).unwrap_or_else(|| "???".into()),
815 fn fetch_cloned_fixed_offset_var<'a, 'tcx>(
816 cx: &LateContext<'a, 'tcx>,
819 ) -> Option<FixedOffsetVar> {
821 if let ExprKind::MethodCall(ref method, _, ref args) = expr.node;
822 if method.ident.name == "clone";
824 if let Some(arg) = args.get(0);
826 return get_fixed_offset_var(cx, arg, var);
830 get_fixed_offset_var(cx, expr, var)
833 fn get_indexed_assignments<'a, 'tcx>(
834 cx: &LateContext<'a, 'tcx>,
837 ) -> Vec<(FixedOffsetVar, FixedOffsetVar)> {
838 fn get_assignment<'a, 'tcx>(
839 cx: &LateContext<'a, 'tcx>,
842 ) -> Option<(FixedOffsetVar, FixedOffsetVar)> {
843 if let ExprKind::Assign(ref lhs, ref rhs) = e.node {
844 match (get_fixed_offset_var(cx, lhs, var), fetch_cloned_fixed_offset_var(cx, rhs, var)) {
845 (Some(offset_left), Some(offset_right)) => {
846 // Source and destination must be different
847 if offset_left.var_name == offset_right.var_name {
850 Some((offset_left, offset_right))
860 if let ExprKind::Block(ref b, _) = body.node {
869 .map(|stmt| match stmt.node {
870 StmtKind::Decl(..) => None,
871 StmtKind::Expr(ref e, _node_id) | StmtKind::Semi(ref e, _node_id) => Some(get_assignment(cx, e, var)),
876 .map(|e| Some(get_assignment(cx, &*e, var))),
879 .collect::<Option<Vec<_>>>()
880 .unwrap_or_else(|| vec![])
882 get_assignment(cx, body, var).into_iter().collect()
886 /// Check for for loops that sequentially copy items from one slice-like
887 /// object to another.
888 fn detect_manual_memcpy<'a, 'tcx>(
889 cx: &LateContext<'a, 'tcx>,
895 if let Some(higher::Range {
899 }) = higher::range(cx, arg)
901 // the var must be a single name
902 if let PatKind::Binding(_, canonical_id, _, _) = pat.node {
903 let print_sum = |arg1: &Offset, arg2: &Offset| -> String {
904 match (&arg1.value[..], arg1.negate, &arg2.value[..], arg2.negate) {
905 ("0", _, "0", _) => "".into(),
906 ("0", _, x, false) | (x, false, "0", false) => x.into(),
907 ("0", _, x, true) | (x, false, "0", true) => format!("-{}", x),
908 (x, false, y, false) => format!("({} + {})", x, y),
909 (x, false, y, true) => format!("({} - {})", x, y),
910 (x, true, y, false) => format!("({} - {})", y, x),
911 (x, true, y, true) => format!("-({} + {})", x, y),
915 let print_limit = |end: &Option<&Expr>, offset: Offset, var_name: &str| if let Some(end) = *end {
917 if let ExprKind::MethodCall(ref method, _, ref len_args) = end.node;
918 if method.ident.name == "len";
919 if len_args.len() == 1;
920 if let Some(arg) = len_args.get(0);
921 if snippet(cx, arg.span, "??") == var_name;
923 return if offset.negate {
924 format!("({} - {})", snippet(cx, end.span, "<src>.len()"), offset.value)
931 let end_str = match limits {
932 ast::RangeLimits::Closed => {
933 let end = sugg::Sugg::hir(cx, end, "<count>");
934 format!("{}", end + sugg::ONE)
936 ast::RangeLimits::HalfOpen => format!("{}", snippet(cx, end.span, "..")),
939 print_sum(&Offset::positive(end_str), &offset)
944 // The only statements in the for loops can be indexed assignments from
945 // indexed retrievals.
946 let manual_copies = get_indexed_assignments(cx, body, canonical_id);
948 let big_sugg = manual_copies
950 .map(|(dst_var, src_var)| {
951 let start_str = Offset::positive(snippet_opt(cx, start.span).unwrap_or_else(|| "".into()));
952 let dst_offset = print_sum(&start_str, &dst_var.offset);
953 let dst_limit = print_limit(end, dst_var.offset, &dst_var.var_name);
954 let src_offset = print_sum(&start_str, &src_var.offset);
955 let src_limit = print_limit(end, src_var.offset, &src_var.var_name);
956 let dst = if dst_offset == "" && dst_limit == "" {
959 format!("{}[{}..{}]", dst_var.var_name, dst_offset, dst_limit)
962 format!("{}.clone_from_slice(&{}[{}..{}])", dst, src_var.var_name, src_offset, src_limit)
966 if !big_sugg.is_empty() {
971 "it looks like you're manually copying between slices",
972 "try replacing the loop by",
980 /// Check for looping over a range and then indexing a sequence with it.
981 /// The iteratee must be a range literal.
982 fn check_for_loop_range<'a, 'tcx>(
983 cx: &LateContext<'a, 'tcx>,
989 if let Some(higher::Range {
993 }) = higher::range(cx, arg)
995 // the var must be a single name
996 if let PatKind::Binding(_, canonical_id, ident, _) = pat.node {
997 let mut visitor = VarVisitor {
1000 indexed_mut: HashSet::new(),
1001 indexed_indirectly: HashMap::new(),
1002 indexed_directly: HashMap::new(),
1003 referenced: HashSet::new(),
1005 prefer_mutable: false,
1007 walk_expr(&mut visitor, body);
1009 // linting condition: we only indexed one variable, and indexed it directly
1010 if visitor.indexed_indirectly.is_empty() && visitor.indexed_directly.len() == 1 {
1011 let (indexed, indexed_extent) = visitor
1015 .expect("already checked that we have exactly 1 element");
1017 // ensure that the indexed variable was declared before the loop, see #601
1018 if let Some(indexed_extent) = indexed_extent {
1019 let parent_id = cx.tcx.hir.get_parent(expr.id);
1020 let parent_def_id = cx.tcx.hir.local_def_id(parent_id);
1021 let region_scope_tree = cx.tcx.region_scope_tree(parent_def_id);
1022 let pat_extent = region_scope_tree.var_scope(pat.hir_id.local_id);
1023 if region_scope_tree.is_subscope_of(indexed_extent, pat_extent) {
1028 // don't lint if the container that is indexed into is also used without
1030 if visitor.referenced.contains(&indexed) {
1034 let starts_at_zero = is_integer_literal(start, 0);
1036 let skip = if starts_at_zero {
1039 format!(".skip({})", snippet(cx, start.span, ".."))
1042 let take = if let Some(end) = *end {
1043 if is_len_call(end, indexed) {
1047 ast::RangeLimits::Closed => {
1048 let end = sugg::Sugg::hir(cx, end, "<count>");
1049 format!(".take({})", end + sugg::ONE)
1051 ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, end.span, "..")),
1058 let (ref_mut, method) = if visitor.indexed_mut.contains(&indexed) {
1059 ("mut ", "iter_mut")
1064 if visitor.nonindex {
1067 NEEDLESS_RANGE_LOOP,
1069 &format!("the loop variable `{}` is used to index `{}`", ident.name, indexed),
1073 "consider using an iterator".to_string(),
1075 (pat.span, format!("({}, <item>)", ident.name)),
1076 (arg.span, format!("{}.{}().enumerate(){}{}", indexed, method, take, skip)),
1082 let repl = if starts_at_zero && take.is_empty() {
1083 format!("&{}{}", ref_mut, indexed)
1085 format!("{}.{}(){}{}", indexed, method, take, skip)
1090 NEEDLESS_RANGE_LOOP,
1092 &format!("the loop variable `{}` is only used to index `{}`.", ident.name, indexed),
1096 "consider using an iterator".to_string(),
1097 vec![(pat.span, "<item>".to_string()), (arg.span, repl)],
1107 fn is_len_call(expr: &Expr, var: Name) -> bool {
1109 if let ExprKind::MethodCall(ref method, _, ref len_args) = expr.node;
1110 if len_args.len() == 1;
1111 if method.ident.name == "len";
1112 if let ExprKind::Path(QPath::Resolved(_, ref path)) = len_args[0].node;
1113 if path.segments.len() == 1;
1114 if path.segments[0].ident.name == var;
1123 fn check_for_loop_reverse_range<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arg: &'tcx Expr, expr: &'tcx Expr) {
1124 // if this for loop is iterating over a two-sided range...
1125 if let Some(higher::Range {
1129 }) = higher::range(cx, arg)
1131 // ...and both sides are compile-time constant integers...
1132 if let Some((start_idx, _)) = constant(cx, cx.tables, start) {
1133 if let Some((end_idx, _)) = constant(cx, cx.tables, end) {
1134 // ...and the start index is greater than the end index,
1135 // this loop will never run. This is often confusing for developers
1136 // who think that this will iterate from the larger value to the
1138 let ty = cx.tables.expr_ty(start);
1139 let (sup, eq) = match (start_idx, end_idx) {
1141 Constant::Int(start_idx),
1142 Constant::Int(end_idx),
1143 ) => (match ty.sty {
1144 ty::TyInt(ity) => sext(cx.tcx, start_idx, ity) > sext(cx.tcx, end_idx, ity),
1145 ty::TyUint(_) => start_idx > end_idx,
1147 }, start_idx == end_idx),
1148 _ => (false, false),
1152 let start_snippet = snippet(cx, start.span, "_");
1153 let end_snippet = snippet(cx, end.span, "_");
1154 let dots = if limits == ast::RangeLimits::Closed {
1164 "this range is empty so this for loop will never run",
1168 "consider using the following if you are attempting to iterate over this \
1171 "({end}{dots}{start}).rev()",
1174 start = start_snippet
1179 } else if eq && limits != ast::RangeLimits::Closed {
1180 // if they are equal, it's also problematic - this loop
1186 "this range is empty so this for loop will never run",
1194 fn lint_iter_method(cx: &LateContext<'_, '_>, args: &[Expr], arg: &Expr, method_name: &str) {
1195 let object = snippet(cx, args[0].span, "_");
1196 let muta = if method_name == "iter_mut" {
1205 "it is more idiomatic to loop over references to containers instead of using explicit \
1207 "to write this more concisely, try",
1208 format!("&{}{}", muta, object),
1212 fn check_for_loop_arg(cx: &LateContext<'_, '_>, pat: &Pat, arg: &Expr, expr: &Expr) {
1213 let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
1214 if let ExprKind::MethodCall(ref method, _, ref args) = arg.node {
1215 // just the receiver, no arguments
1216 if args.len() == 1 {
1217 let method_name = &*method.ident.as_str();
1218 // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
1219 if method_name == "iter" || method_name == "iter_mut" {
1220 if is_ref_iterable_type(cx, &args[0]) {
1221 lint_iter_method(cx, args, arg, method_name);
1223 } else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
1224 let def_id = cx.tables.type_dependent_defs()[arg.hir_id].def_id();
1225 let substs = cx.tables.node_substs(arg.hir_id);
1226 let method_type = cx.tcx.type_of(def_id).subst(cx.tcx, substs);
1228 let fn_arg_tys = method_type.fn_sig(cx.tcx).inputs();
1229 assert_eq!(fn_arg_tys.skip_binder().len(), 1);
1230 if fn_arg_tys.skip_binder()[0].is_region_ptr() {
1231 match cx.tables.expr_ty(&args[0]).sty {
1232 // If the length is greater than 32 no traits are implemented for array and
1233 // therefore we cannot use `&`.
1234 ty::TypeVariants::TyArray(_, size) if size.assert_usize(cx.tcx).expect("array size") > 32 => (),
1235 _ => lint_iter_method(cx, args, arg, method_name),
1238 let object = snippet(cx, args[0].span, "_");
1241 EXPLICIT_INTO_ITER_LOOP,
1243 "it is more idiomatic to loop over containers instead of using explicit \
1244 iteration methods`",
1245 "to write this more concisely, try",
1249 } else if method_name == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
1254 "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
1255 probably not what you want",
1257 next_loop_linted = true;
1261 if !next_loop_linted {
1262 check_arg_type(cx, pat, arg);
1266 /// Check for `for` loops over `Option`s and `Results`
1267 fn check_arg_type(cx: &LateContext<'_, '_>, pat: &Pat, arg: &Expr) {
1268 let ty = cx.tables.expr_ty(arg);
1269 if match_type(cx, ty, &paths::OPTION) {
1272 FOR_LOOP_OVER_OPTION,
1275 "for loop over `{0}`, which is an `Option`. This is more readably written as an \
1276 `if let` statement.",
1277 snippet(cx, arg.span, "_")
1280 "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
1281 snippet(cx, pat.span, "_"),
1282 snippet(cx, arg.span, "_")
1285 } else if match_type(cx, ty, &paths::RESULT) {
1288 FOR_LOOP_OVER_RESULT,
1291 "for loop over `{0}`, which is a `Result`. This is more readably written as an \
1292 `if let` statement.",
1293 snippet(cx, arg.span, "_")
1296 "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
1297 snippet(cx, pat.span, "_"),
1298 snippet(cx, arg.span, "_")
1304 fn check_for_loop_explicit_counter<'a, 'tcx>(
1305 cx: &LateContext<'a, 'tcx>,
1310 // Look for variables that are incremented once per loop iteration.
1311 let mut visitor = IncrementVisitor {
1313 states: HashMap::new(),
1317 walk_expr(&mut visitor, body);
1319 // For each candidate, check the parent block to see if
1320 // it's initialized to zero at the start of the loop.
1321 let map = &cx.tcx.hir;
1322 let parent_scope = map.get_enclosing_scope(expr.id)
1323 .and_then(|id| map.get_enclosing_scope(id));
1324 if let Some(parent_id) = parent_scope {
1325 if let NodeBlock(block) = map.get(parent_id) {
1326 for (id, _) in visitor
1329 .filter(|&(_, v)| *v == VarState::IncrOnce)
1331 let mut visitor2 = InitializeVisitor {
1335 state: VarState::IncrOnce,
1340 walk_block(&mut visitor2, block);
1342 if visitor2.state == VarState::Warn {
1343 if let Some(name) = visitor2.name {
1346 EXPLICIT_COUNTER_LOOP,
1349 "the variable `{0}` is used as a loop counter. Consider using `for ({0}, \
1350 item) in {1}.enumerate()` or similar iterators",
1352 snippet(cx, arg.span, "_")
1362 /// Check for the `FOR_KV_MAP` lint.
1363 fn check_for_loop_over_map_kv<'a, 'tcx>(
1364 cx: &LateContext<'a, 'tcx>,
1370 let pat_span = pat.span;
1372 if let PatKind::Tuple(ref pat, _) = pat.node {
1374 let arg_span = arg.span;
1375 let (new_pat_span, kind, ty, mutbl) = match cx.tables.expr_ty(arg).sty {
1376 ty::TyRef(_, ty, mutbl) => match (&pat[0].node, &pat[1].node) {
1377 (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", ty, mutbl),
1378 (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", ty, MutImmutable),
1383 let mutbl = match mutbl {
1385 MutMutable => "_mut",
1387 let arg = match arg.node {
1388 ExprKind::AddrOf(_, ref expr) => &**expr,
1392 if match_type(cx, ty, &paths::HASHMAP) || match_type(cx, ty, &paths::BTREEMAP) {
1397 &format!("you seem to want to iterate on a map's {}s", kind),
1399 let map = sugg::Sugg::hir(cx, arg, "map");
1402 "use the corresponding method".into(),
1404 (pat_span, snippet(cx, new_pat_span, kind).into_owned()),
1405 (arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)),
1415 struct MutatePairDelegate {
1416 node_id_low: Option<NodeId>,
1417 node_id_high: Option<NodeId>,
1418 span_low: Option<Span>,
1419 span_high: Option<Span>,
1422 impl<'tcx> Delegate<'tcx> for MutatePairDelegate {
1423 fn consume(&mut self, _: NodeId, _: Span, _: &cmt_<'tcx>, _: ConsumeMode) {}
1425 fn matched_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: MatchMode) {}
1427 fn consume_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: ConsumeMode) {}
1429 fn borrow(&mut self, _: NodeId, sp: Span, cmt: &cmt_<'tcx>, _: ty::Region<'_>, bk: ty::BorrowKind, _: LoanCause) {
1430 if let ty::BorrowKind::MutBorrow = bk {
1431 if let Categorization::Local(id) = cmt.cat {
1432 if Some(id) == self.node_id_low {
1433 self.span_low = Some(sp)
1435 if Some(id) == self.node_id_high {
1436 self.span_high = Some(sp)
1442 fn mutate(&mut self, _: NodeId, sp: Span, cmt: &cmt_<'tcx>, _: MutateMode) {
1443 if let Categorization::Local(id) = cmt.cat {
1444 if Some(id) == self.node_id_low {
1445 self.span_low = Some(sp)
1447 if Some(id) == self.node_id_high {
1448 self.span_high = Some(sp)
1453 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
1456 impl<'tcx> MutatePairDelegate {
1457 fn mutation_span(&self) -> (Option<Span>, Option<Span>) {
1458 (self.span_low, self.span_high)
1462 fn check_for_mut_range_bound(cx: &LateContext<'_, '_>, arg: &Expr, body: &Expr) {
1463 if let Some(higher::Range {
1467 }) = higher::range(cx, arg)
1470 check_for_mutability(cx, start),
1471 check_for_mutability(cx, end),
1473 if mut_ids[0].is_some() || mut_ids[1].is_some() {
1474 let (span_low, span_high) = check_for_mutation(cx, body, &mut_ids);
1475 mut_warn_with_span(cx, span_low);
1476 mut_warn_with_span(cx, span_high);
1481 fn mut_warn_with_span(cx: &LateContext<'_, '_>, span: Option<Span>) {
1482 if let Some(sp) = span {
1487 "attempt to mutate range bound within loop; note that the range of the loop is unchanged",
1492 fn check_for_mutability(cx: &LateContext<'_, '_>, bound: &Expr) -> Option<NodeId> {
1494 if let ExprKind::Path(ref qpath) = bound.node;
1495 if let QPath::Resolved(None, _) = *qpath;
1497 let def = cx.tables.qpath_def(qpath, bound.hir_id);
1498 if let Def::Local(node_id) = def {
1499 let node_str = cx.tcx.hir.get(node_id);
1501 if let map::Node::NodeBinding(pat) = node_str;
1502 if let PatKind::Binding(bind_ann, _, _, _) = pat.node;
1503 if let BindingAnnotation::Mutable = bind_ann;
1505 return Some(node_id);
1514 fn check_for_mutation(cx: &LateContext<'_, '_>, body: &Expr, bound_ids: &[Option<NodeId>]) -> (Option<Span>, Option<Span>) {
1515 let mut delegate = MutatePairDelegate {
1516 node_id_low: bound_ids[0],
1517 node_id_high: bound_ids[1],
1521 let def_id = def_id::DefId::local(body.hir_id.owner);
1522 let region_scope_tree = &cx.tcx.region_scope_tree(def_id);
1523 ExprUseVisitor::new(&mut delegate, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None).walk_expr(body);
1524 delegate.mutation_span()
1527 /// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`.
1528 fn pat_is_wild<'tcx>(pat: &'tcx PatKind, body: &'tcx Expr) -> bool {
1530 PatKind::Wild => true,
1531 PatKind::Binding(_, _, ident, None) if ident.as_str().starts_with('_') => {
1532 let mut visitor = UsedVisitor {
1536 walk_expr(&mut visitor, body);
1543 struct UsedVisitor {
1544 var: ast::Name, // var to look for
1545 used: bool, // has the var been used otherwise?
1548 impl<'tcx> Visitor<'tcx> for UsedVisitor {
1549 fn visit_expr(&mut self, expr: &'tcx Expr) {
1550 if match_var(expr, self.var) {
1553 walk_expr(self, expr);
1557 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1558 NestedVisitorMap::None
1562 struct LocalUsedVisitor<'a, 'tcx: 'a> {
1563 cx: &'a LateContext<'a, 'tcx>,
1568 impl<'a, 'tcx: 'a> Visitor<'tcx> for LocalUsedVisitor<'a, 'tcx> {
1569 fn visit_expr(&mut self, expr: &'tcx Expr) {
1570 if same_var(self.cx, expr, self.local) {
1573 walk_expr(self, expr);
1577 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1578 NestedVisitorMap::None
1582 struct VarVisitor<'a, 'tcx: 'a> {
1583 /// context reference
1584 cx: &'a LateContext<'a, 'tcx>,
1585 /// var name to look for as index
1587 /// indexed variables that are used mutably
1588 indexed_mut: HashSet<Name>,
1589 /// indirectly indexed variables (`v[(i + 4) % N]`), the extend is `None` for global
1590 indexed_indirectly: HashMap<Name, Option<region::Scope>>,
1591 /// subset of `indexed` of vars that are indexed directly: `v[i]`
1592 /// this will not contain cases like `v[calc_index(i)]` or `v[(i + 4) % N]`
1593 indexed_directly: HashMap<Name, Option<region::Scope>>,
1594 /// Any names that are used outside an index operation.
1595 /// Used to detect things like `&mut vec` used together with `vec[i]`
1596 referenced: HashSet<Name>,
1597 /// has the loop variable been used in expressions other than the index of
1600 /// Whether we are inside the `$` in `&mut $` or `$ = foo` or `$.bar`, where bar
1601 /// takes `&mut self`
1602 prefer_mutable: bool,
1605 impl<'a, 'tcx> VarVisitor<'a, 'tcx> {
1606 fn check(&mut self, idx: &'tcx Expr, seqexpr: &'tcx Expr, expr: &'tcx Expr) -> bool {
1608 // the indexed container is referenced by a name
1609 if let ExprKind::Path(ref seqpath) = seqexpr.node;
1610 if let QPath::Resolved(None, ref seqvar) = *seqpath;
1611 if seqvar.segments.len() == 1;
1613 let index_used_directly = same_var(self.cx, idx, self.var);
1614 let indexed_indirectly = {
1615 let mut used_visitor = LocalUsedVisitor {
1620 walk_expr(&mut used_visitor, idx);
1624 if indexed_indirectly || index_used_directly {
1625 if self.prefer_mutable {
1626 self.indexed_mut.insert(seqvar.segments[0].ident.name);
1628 let def = self.cx.tables.qpath_def(seqpath, seqexpr.hir_id);
1630 Def::Local(node_id) | Def::Upvar(node_id, ..) => {
1631 let hir_id = self.cx.tcx.hir.node_to_hir_id(node_id);
1633 let parent_id = self.cx.tcx.hir.get_parent(expr.id);
1634 let parent_def_id = self.cx.tcx.hir.local_def_id(parent_id);
1635 let extent = self.cx.tcx.region_scope_tree(parent_def_id).var_scope(hir_id.local_id);
1636 if indexed_indirectly {
1637 self.indexed_indirectly.insert(seqvar.segments[0].ident.name, Some(extent));
1639 if index_used_directly {
1640 self.indexed_directly.insert(seqvar.segments[0].ident.name, Some(extent));
1642 return false; // no need to walk further *on the variable*
1644 Def::Static(..) | Def::Const(..) => {
1645 if indexed_indirectly {
1646 self.indexed_indirectly.insert(seqvar.segments[0].ident.name, None);
1648 if index_used_directly {
1649 self.indexed_directly.insert(seqvar.segments[0].ident.name, None);
1651 return false; // no need to walk further *on the variable*
1662 impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
1663 fn visit_expr(&mut self, expr: &'tcx Expr) {
1666 if let ExprKind::MethodCall(ref meth, _, ref args) = expr.node;
1667 if (meth.ident.name == "index" && match_trait_method(self.cx, expr, &paths::INDEX))
1668 || (meth.ident.name == "index_mut" && match_trait_method(self.cx, expr, &paths::INDEX_MUT));
1669 if !self.check(&args[1], &args[0], expr);
1675 if let ExprKind::Index(ref seqexpr, ref idx) = expr.node;
1676 if !self.check(idx, seqexpr, expr);
1681 // directly using a variable
1682 if let ExprKind::Path(ref qpath) = expr.node;
1683 if let QPath::Resolved(None, ref path) = *qpath;
1684 if path.segments.len() == 1;
1685 if let Def::Local(local_id) = self.cx.tables.qpath_def(qpath, expr.hir_id);
1687 if local_id == self.var {
1688 // we are not indexing anything, record that
1689 self.nonindex = true;
1691 // not the correct variable, but still a variable
1692 self.referenced.insert(path.segments[0].ident.name);
1696 let old = self.prefer_mutable;
1698 ExprKind::AssignOp(_, ref lhs, ref rhs) |
1699 ExprKind::Assign(ref lhs, ref rhs) => {
1700 self.prefer_mutable = true;
1701 self.visit_expr(lhs);
1702 self.prefer_mutable = false;
1703 self.visit_expr(rhs);
1705 ExprKind::AddrOf(mutbl, ref expr) => {
1706 if mutbl == MutMutable {
1707 self.prefer_mutable = true;
1709 self.visit_expr(expr);
1711 ExprKind::Call(ref f, ref args) => {
1714 let ty = self.cx.tables.expr_ty_adjusted(expr);
1715 self.prefer_mutable = false;
1716 if let ty::TyRef(_, _, mutbl) = ty.sty {
1717 if mutbl == MutMutable {
1718 self.prefer_mutable = true;
1721 self.visit_expr(expr);
1724 ExprKind::MethodCall(_, _, ref args) => {
1725 let def_id = self.cx.tables.type_dependent_defs()[expr.hir_id].def_id();
1726 for (ty, expr) in self.cx.tcx.fn_sig(def_id).inputs().skip_binder().iter().zip(args) {
1727 self.prefer_mutable = false;
1728 if let ty::TyRef(_, _, mutbl) = ty.sty {
1729 if mutbl == MutMutable {
1730 self.prefer_mutable = true;
1733 self.visit_expr(expr);
1736 _ => walk_expr(self, expr),
1738 self.prefer_mutable = old;
1740 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1741 NestedVisitorMap::None
1745 fn is_iterator_used_after_while_let<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, iter_expr: &'tcx Expr) -> bool {
1746 let def_id = match var_def_id(cx, iter_expr) {
1748 None => return false,
1750 let mut visitor = VarUsedAfterLoopVisitor {
1753 iter_expr_id: iter_expr.id,
1754 past_while_let: false,
1755 var_used_after_while_let: false,
1757 if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
1758 walk_block(&mut visitor, enclosing_block);
1760 visitor.var_used_after_while_let
1763 struct VarUsedAfterLoopVisitor<'a, 'tcx: 'a> {
1764 cx: &'a LateContext<'a, 'tcx>,
1766 iter_expr_id: NodeId,
1767 past_while_let: bool,
1768 var_used_after_while_let: bool,
1771 impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
1772 fn visit_expr(&mut self, expr: &'tcx Expr) {
1773 if self.past_while_let {
1774 if Some(self.def_id) == var_def_id(self.cx, expr) {
1775 self.var_used_after_while_let = true;
1777 } else if self.iter_expr_id == expr.id {
1778 self.past_while_let = true;
1780 walk_expr(self, expr);
1782 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1783 NestedVisitorMap::None
1788 /// Return true if the type of expr is one that provides `IntoIterator` impls
1789 /// for `&T` and `&mut T`, such as `Vec`.
1790 #[cfg_attr(rustfmt, rustfmt_skip)]
1791 fn is_ref_iterable_type(cx: &LateContext<'_, '_>, e: &Expr) -> bool {
1792 // no walk_ptrs_ty: calling iter() on a reference can make sense because it
1793 // will allow further borrows afterwards
1794 let ty = cx.tables.expr_ty(e);
1795 is_iterable_array(ty, cx) ||
1796 match_type(cx, ty, &paths::VEC) ||
1797 match_type(cx, ty, &paths::LINKED_LIST) ||
1798 match_type(cx, ty, &paths::HASHMAP) ||
1799 match_type(cx, ty, &paths::HASHSET) ||
1800 match_type(cx, ty, &paths::VEC_DEQUE) ||
1801 match_type(cx, ty, &paths::BINARY_HEAP) ||
1802 match_type(cx, ty, &paths::BTREEMAP) ||
1803 match_type(cx, ty, &paths::BTREESET)
1806 fn is_iterable_array(ty: Ty<'_>, cx: &LateContext<'_, '_>) -> bool {
1807 // IntoIterator is currently only implemented for array sizes <= 32 in rustc
1809 ty::TyArray(_, n) => (0..=32).contains(&n.assert_usize(cx.tcx).expect("array length")),
1814 /// If a block begins with a statement (possibly a `let` binding) and has an
1815 /// expression, return it.
1816 fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
1817 if block.stmts.is_empty() {
1820 if let StmtKind::Decl(ref decl, _) = block.stmts[0].node {
1821 if let DeclKind::Local(ref local) = decl.node {
1822 if let Some(ref expr) = local.init {
1835 /// If a block begins with an expression (with or without semicolon), return it.
1836 fn extract_first_expr(block: &Block) -> Option<&Expr> {
1838 Some(ref expr) if block.stmts.is_empty() => Some(expr),
1839 None if !block.stmts.is_empty() => match block.stmts[0].node {
1840 StmtKind::Expr(ref expr, _) | StmtKind::Semi(ref expr, _) => Some(expr),
1841 StmtKind::Decl(..) => None,
1847 /// Return true if expr contains a single break expr without destination label
1849 /// passed expression. The expression may be within a block.
1850 fn is_simple_break_expr(expr: &Expr) -> bool {
1852 ExprKind::Break(dest, ref passed_expr) if dest.label.is_none() && passed_expr.is_none() => true,
1853 ExprKind::Block(ref b, _) => match extract_first_expr(b) {
1854 Some(subexpr) => is_simple_break_expr(subexpr),
1861 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
1862 // incremented exactly once in the loop body, and initialized to zero
1863 // at the start of the loop.
1864 #[derive(PartialEq)]
1866 Initial, // Not examined yet
1867 IncrOnce, // Incremented exactly once, may be a loop counter
1868 Declared, // Declared but not (yet) initialized to zero
1873 /// Scan a for loop for variables that are incremented exactly once.
1874 struct IncrementVisitor<'a, 'tcx: 'a> {
1875 cx: &'a LateContext<'a, 'tcx>, // context reference
1876 states: HashMap<NodeId, VarState>, // incremented variables
1877 depth: u32, // depth of conditional expressions
1881 impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
1882 fn visit_expr(&mut self, expr: &'tcx Expr) {
1887 // If node is a variable
1888 if let Some(def_id) = var_def_id(self.cx, expr) {
1889 if let Some(parent) = get_parent_expr(self.cx, expr) {
1890 let state = self.states.entry(def_id).or_insert(VarState::Initial);
1893 ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1894 if lhs.id == expr.id {
1895 if op.node == BinOpKind::Add && is_integer_literal(rhs, 1) {
1896 *state = match *state {
1897 VarState::Initial if self.depth == 0 => VarState::IncrOnce,
1898 _ => VarState::DontWarn,
1901 // Assigned some other value
1902 *state = VarState::DontWarn;
1906 ExprKind::Assign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
1907 ExprKind::AddrOf(mutability, _) if mutability == MutMutable => *state = VarState::DontWarn,
1911 } else if is_loop(expr) {
1912 self.states.clear();
1915 } else if is_conditional(expr) {
1917 walk_expr(self, expr);
1921 walk_expr(self, expr);
1923 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1924 NestedVisitorMap::None
1928 /// Check whether a variable is initialized to zero at the start of a loop.
1929 struct InitializeVisitor<'a, 'tcx: 'a> {
1930 cx: &'a LateContext<'a, 'tcx>, // context reference
1931 end_expr: &'tcx Expr, // the for loop. Stop scanning here.
1935 depth: u32, // depth of conditional expressions
1939 impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
1940 fn visit_decl(&mut self, decl: &'tcx Decl) {
1941 // Look for declarations of the variable
1942 if let DeclKind::Local(ref local) = decl.node {
1943 if local.pat.id == self.var_id {
1944 if let PatKind::Binding(_, _, ident, _) = local.pat.node {
1945 self.name = Some(ident.name);
1947 self.state = if let Some(ref init) = local.init {
1948 if is_integer_literal(init, 0) {
1959 walk_decl(self, decl);
1962 fn visit_expr(&mut self, expr: &'tcx Expr) {
1963 if self.state == VarState::DontWarn {
1966 if SpanlessEq::new(self.cx).eq_expr(&expr, self.end_expr) {
1967 self.past_loop = true;
1970 // No need to visit expressions before the variable is
1972 if self.state == VarState::IncrOnce {
1976 // If node is the desired variable, see how it's used
1977 if var_def_id(self.cx, expr) == Some(self.var_id) {
1978 if let Some(parent) = get_parent_expr(self.cx, expr) {
1980 ExprKind::AssignOp(_, ref lhs, _) if lhs.id == expr.id => {
1981 self.state = VarState::DontWarn;
1983 ExprKind::Assign(ref lhs, ref rhs) if lhs.id == expr.id => {
1984 self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
1990 ExprKind::AddrOf(mutability, _) if mutability == MutMutable => self.state = VarState::DontWarn,
1996 self.state = VarState::DontWarn;
1999 } else if !self.past_loop && is_loop(expr) {
2000 self.state = VarState::DontWarn;
2002 } else if is_conditional(expr) {
2004 walk_expr(self, expr);
2008 walk_expr(self, expr);
2010 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2011 NestedVisitorMap::None
2015 fn var_def_id(cx: &LateContext<'_, '_>, expr: &Expr) -> Option<NodeId> {
2016 if let ExprKind::Path(ref qpath) = expr.node {
2017 let path_res = cx.tables.qpath_def(qpath, expr.hir_id);
2018 if let Def::Local(node_id) = path_res {
2019 return Some(node_id);
2025 fn is_loop(expr: &Expr) -> bool {
2027 ExprKind::Loop(..) | ExprKind::While(..) => true,
2032 fn is_conditional(expr: &Expr) -> bool {
2034 ExprKind::If(..) | ExprKind::Match(..) => true,
2039 fn is_nested(cx: &LateContext<'_, '_>, match_expr: &Expr, iter_expr: &Expr) -> bool {
2041 if let Some(loop_block) = get_enclosing_block(cx, match_expr.id);
2042 if let Some(map::Node::NodeExpr(loop_expr)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(loop_block.id));
2044 return is_loop_nested(cx, loop_expr, iter_expr)
2050 fn is_loop_nested(cx: &LateContext<'_, '_>, loop_expr: &Expr, iter_expr: &Expr) -> bool {
2051 let mut id = loop_expr.id;
2052 let iter_name = if let Some(name) = path_name(iter_expr) {
2058 let parent = cx.tcx.hir.get_parent_node(id);
2062 match cx.tcx.hir.find(parent) {
2063 Some(NodeExpr(expr)) => match expr.node {
2064 ExprKind::Loop(..) | ExprKind::While(..) => {
2069 Some(NodeBlock(block)) => {
2070 let mut block_visitor = LoopNestVisitor {
2072 iterator: iter_name,
2075 walk_block(&mut block_visitor, block);
2076 if block_visitor.nesting == RuledOut {
2080 Some(NodeStmt(_)) => (),
2089 #[derive(PartialEq, Eq)]
2091 Unknown, // no nesting detected yet
2092 RuledOut, // the iterator is initialized or assigned within scope
2093 LookFurther, // no nesting detected, no further walk required
2096 use self::Nesting::{LookFurther, RuledOut, Unknown};
2098 struct LoopNestVisitor {
2104 impl<'tcx> Visitor<'tcx> for LoopNestVisitor {
2105 fn visit_stmt(&mut self, stmt: &'tcx Stmt) {
2106 if stmt.node.id() == self.id {
2107 self.nesting = LookFurther;
2108 } else if self.nesting == Unknown {
2109 walk_stmt(self, stmt);
2113 fn visit_expr(&mut self, expr: &'tcx Expr) {
2114 if self.nesting != Unknown {
2117 if expr.id == self.id {
2118 self.nesting = LookFurther;
2122 ExprKind::Assign(ref path, _) | ExprKind::AssignOp(_, ref path, _) => if match_var(path, self.iterator) {
2123 self.nesting = RuledOut;
2125 _ => walk_expr(self, expr),
2129 fn visit_pat(&mut self, pat: &'tcx Pat) {
2130 if self.nesting != Unknown {
2133 if let PatKind::Binding(_, _, span_name, _) = pat.node {
2134 if self.iterator == span_name.name {
2135 self.nesting = RuledOut;
2142 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2143 NestedVisitorMap::None
2147 fn path_name(e: &Expr) -> Option<Name> {
2148 if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.node {
2149 let segments = &path.segments;
2150 if segments.len() == 1 {
2151 return Some(segments[0].ident.name);
2157 fn check_infinite_loop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, cond: &'tcx Expr, expr: &'tcx Expr) {
2158 if constant(cx, cx.tables, cond).is_some() {
2159 // A pure constant condition (e.g. while false) is not linted.
2163 let mut var_visitor = VarCollectorVisitor {
2165 ids: HashSet::new(),
2166 def_ids: HashMap::new(),
2169 var_visitor.visit_expr(cond);
2170 if var_visitor.skip {
2173 let used_in_condition = &var_visitor.ids;
2174 let no_cond_variable_mutated = if let Some(used_mutably) = mutated_variables(expr, cx) {
2175 used_in_condition.is_disjoint(&used_mutably)
2179 let mutable_static_in_cond = var_visitor.def_ids.iter().any(|(_, v)| *v);
2180 if no_cond_variable_mutated && !mutable_static_in_cond {
2183 WHILE_IMMUTABLE_CONDITION,
2185 "Variable in the condition are not mutated in the loop body. This either leads to an infinite or to a never running loop.",
2190 /// Collects the set of variables in an expression
2191 /// Stops analysis if a function call is found
2192 /// Note: In some cases such as `self`, there are no mutable annotation,
2193 /// All variables definition IDs are collected
2194 struct VarCollectorVisitor<'a, 'tcx: 'a> {
2195 cx: &'a LateContext<'a, 'tcx>,
2196 ids: HashSet<NodeId>,
2197 def_ids: HashMap<def_id::DefId, bool>,
2201 impl<'a, 'tcx> VarCollectorVisitor<'a, 'tcx> {
2202 fn insert_def_id(&mut self, ex: &'tcx Expr) {
2204 if let ExprKind::Path(ref qpath) = ex.node;
2205 if let QPath::Resolved(None, _) = *qpath;
2206 let def = self.cx.tables.qpath_def(qpath, ex.hir_id);
2209 Def::Local(node_id) | Def::Upvar(node_id, ..) => {
2210 self.ids.insert(node_id);
2212 Def::Static(def_id, mutable) => {
2213 self.def_ids.insert(def_id, mutable);
2222 impl<'a, 'tcx> Visitor<'tcx> for VarCollectorVisitor<'a, 'tcx> {
2223 fn visit_expr(&mut self, ex: &'tcx Expr) {
2225 ExprKind::Path(_) => self.insert_def_id(ex),
2226 // If there is any function/method call… we just stop analysis
2227 ExprKind::Call(..) | ExprKind::MethodCall(..) => self.skip = true,
2229 _ => walk_expr(self, ex),
2233 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
2234 NestedVisitorMap::None