1 use crate::consts::{constant, Constant};
2 use crate::reexport::Name;
3 use crate::utils::paths;
4 use crate::utils::usage::{is_unused, mutated_variables};
6 get_enclosing_block, get_parent_expr, get_trait_def_id, has_iter_method, higher, implements_trait,
7 is_integer_const, is_no_std_crate, is_refutable, last_path_segment, match_trait_method, match_type, match_var,
8 multispan_sugg, snippet, snippet_opt, snippet_with_applicability, span_lint, span_lint_and_help,
9 span_lint_and_sugg, span_lint_and_then, SpanlessEq,
11 use crate::utils::{is_type_diagnostic_item, qpath_res, same_tys, sext, sugg};
12 use if_chain::if_chain;
14 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
15 use rustc_errors::Applicability;
16 use rustc_hir::def::{DefKind, Res};
17 use rustc_hir::intravisit::{walk_block, walk_expr, walk_pat, walk_stmt, NestedVisitorMap, Visitor};
19 def_id, BinOpKind, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, GenericArg, HirId, LoopSource,
20 MatchSource, Mutability, Node, Pat, PatKind, QPath, Stmt, StmtKind,
22 use rustc_infer::infer::TyCtxtInferExt;
23 use rustc_lint::{LateContext, LateLintPass, LintContext};
24 use rustc_middle::hir::map::Map;
25 use rustc_middle::lint::in_external_macro;
26 use rustc_middle::middle::region;
27 use rustc_middle::ty::{self, Ty};
28 use rustc_session::{declare_lint_pass, declare_tool_lint};
29 use rustc_span::source_map::Span;
30 use rustc_span::BytePos;
31 use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, Place, PlaceBase};
32 use std::iter::{once, Iterator};
35 declare_clippy_lint! {
36 /// **What it does:** Checks for for-loops that manually copy items between
37 /// slices that could be optimized by having a memcpy.
39 /// **Why is this bad?** It is not as fast as a memcpy.
41 /// **Known problems:** None.
45 /// # let src = vec![1];
46 /// # let mut dst = vec![0; 65];
47 /// for i in 0..src.len() {
48 /// dst[i + 64] = src[i];
51 /// Could be written as:
53 /// # let src = vec![1];
54 /// # let mut dst = vec![0; 65];
55 /// dst[64..(src.len() + 64)].clone_from_slice(&src[..]);
59 "manually copying items between slices"
62 declare_clippy_lint! {
63 /// **What it does:** Checks for looping over the range of `0..len` of some
64 /// collection just to get the values by index.
66 /// **Why is this bad?** Just iterating the collection itself makes the intent
67 /// more clear and is probably faster.
69 /// **Known problems:** None.
73 /// let vec = vec!['a', 'b', 'c'];
74 /// for i in 0..vec.len() {
75 /// println!("{}", vec[i]);
78 /// Could be written as:
80 /// let vec = vec!['a', 'b', 'c'];
82 /// println!("{}", i);
85 pub NEEDLESS_RANGE_LOOP,
87 "for-looping over a range of indices where an iterator over items would do"
90 declare_clippy_lint! {
91 /// **What it does:** Checks for loops on `x.iter()` where `&x` will do, and
92 /// suggests the latter.
94 /// **Why is this bad?** Readability.
96 /// **Known problems:** False negatives. We currently only warn on some known
101 /// // with `y` a `Vec` or slice:
102 /// # let y = vec![1];
103 /// for x in y.iter() {
107 /// can be rewritten to
109 /// # let y = vec![1];
114 pub EXPLICIT_ITER_LOOP,
116 "for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
119 declare_clippy_lint! {
120 /// **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and
121 /// suggests the latter.
123 /// **Why is this bad?** Readability.
125 /// **Known problems:** None
129 /// # let y = vec![1];
130 /// // with `y` a `Vec` or slice:
131 /// for x in y.into_iter() {
135 /// can be rewritten to
137 /// # let y = vec![1];
142 pub EXPLICIT_INTO_ITER_LOOP,
144 "for-looping over `_.into_iter()` when `_` would do"
147 declare_clippy_lint! {
148 /// **What it does:** Checks for loops on `x.next()`.
150 /// **Why is this bad?** `next()` returns either `Some(value)` if there was a
151 /// value, or `None` otherwise. The insidious thing is that `Option<_>`
152 /// implements `IntoIterator`, so that possibly one value will be iterated,
153 /// leading to some hard to find bugs. No one will want to write such code
154 /// [except to win an Underhanded Rust
155 /// Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
157 /// **Known problems:** None.
161 /// for x in y.next() {
167 "for-looping over `_.next()` which is probably not intended"
170 declare_clippy_lint! {
171 /// **What it does:** Checks for `for` loops over `Option` values.
173 /// **Why is this bad?** Readability. This is more clearly expressed as an `if
176 /// **Known problems:** None.
180 /// for x in option {
187 /// if let Some(x) = option {
191 pub FOR_LOOP_OVER_OPTION,
193 "for-looping over an `Option`, which is more clearly expressed as an `if let`"
196 declare_clippy_lint! {
197 /// **What it does:** Checks for `for` loops over `Result` values.
199 /// **Why is this bad?** Readability. This is more clearly expressed as an `if
202 /// **Known problems:** None.
206 /// for x in result {
213 /// if let Ok(x) = result {
217 pub FOR_LOOP_OVER_RESULT,
219 "for-looping over a `Result`, which is more clearly expressed as an `if let`"
222 declare_clippy_lint! {
223 /// **What it does:** Detects `loop + match` combinations that are easier
224 /// written as a `while let` loop.
226 /// **Why is this bad?** The `while let` loop is usually shorter and more
229 /// **Known problems:** Sometimes the wrong binding is displayed (#383).
233 /// # let y = Some(1);
235 /// let x = match y {
239 /// // .. do something with x
241 /// // is easier written as
242 /// while let Some(x) = y {
243 /// // .. do something with x
248 "`loop { if let { ... } else break }`, which can be written as a `while let` loop"
251 declare_clippy_lint! {
252 /// **What it does:** Checks for functions collecting an iterator when collect
255 /// **Why is this bad?** `collect` causes the allocation of a new data structure,
256 /// when this allocation may not be needed.
258 /// **Known problems:**
263 /// # let iterator = vec![1].into_iter();
264 /// let len = iterator.clone().collect::<Vec<_>>().len();
266 /// let len = iterator.count();
268 pub NEEDLESS_COLLECT,
270 "collecting an iterator when collect is not needed"
273 declare_clippy_lint! {
274 /// **What it does:** Checks for loops over ranges `x..y` where both `x` and `y`
275 /// are constant and `x` is greater or equal to `y`, unless the range is
276 /// reversed or has a negative `.step_by(_)`.
278 /// **Why is it bad?** Such loops will either be skipped or loop until
279 /// wrap-around (in debug code, this may `panic!()`). Both options are probably
282 /// **Known problems:** The lint cannot catch loops over dynamically defined
283 /// ranges. Doing this would require simulating all possible inputs and code
284 /// paths through the program, which would be complex and error-prone.
288 /// for x in 5..10 - 5 {
290 /// } // oops, stray `-`
292 pub REVERSE_RANGE_LOOP,
294 "iteration over an empty range, such as `10..0` or `5..5`"
297 declare_clippy_lint! {
298 /// **What it does:** Checks `for` loops over slices with an explicit counter
299 /// and suggests the use of `.enumerate()`.
301 /// **Why is it bad?** Using `.enumerate()` makes the intent more clear,
302 /// declutters the code and may be faster in some instances.
304 /// **Known problems:** None.
308 /// # let v = vec![1];
309 /// # fn bar(bar: usize, baz: usize) {}
316 /// Could be written as
318 /// # let v = vec![1];
319 /// # fn bar(bar: usize, baz: usize) {}
320 /// for (i, item) in v.iter().enumerate() { bar(i, *item); }
322 pub EXPLICIT_COUNTER_LOOP,
324 "for-looping with an explicit counter when `_.enumerate()` would do"
327 declare_clippy_lint! {
328 /// **What it does:** Checks for empty `loop` expressions.
330 /// **Why is this bad?** Those busy loops burn CPU cycles without doing
331 /// anything. Think of the environment and either block on something or at least
332 /// make the thread sleep for some microseconds.
334 /// **Known problems:** None.
342 "empty `loop {}`, which should block or sleep"
345 declare_clippy_lint! {
346 /// **What it does:** Checks for `while let` expressions on iterators.
348 /// **Why is this bad?** Readability. A simple `for` loop is shorter and conveys
349 /// the intent better.
351 /// **Known problems:** None.
355 /// while let Some(val) = iter() {
359 pub WHILE_LET_ON_ITERATOR,
361 "using a while-let loop instead of a for loop on an iterator"
364 declare_clippy_lint! {
365 /// **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and
366 /// ignoring either the keys or values.
368 /// **Why is this bad?** Readability. There are `keys` and `values` methods that
369 /// can be used to express that don't need the values or keys.
371 /// **Known problems:** None.
375 /// for (k, _) in &map {
380 /// could be replaced by
383 /// for k in map.keys() {
389 "looping on a map using `iter` when `keys` or `values` would do"
392 declare_clippy_lint! {
393 /// **What it does:** Checks for loops that will always `break`, `return` or
394 /// `continue` an outer loop.
396 /// **Why is this bad?** This loop never loops, all it does is obfuscating the
399 /// **Known problems:** None
410 "any loop that will always `break` or `return`"
413 declare_clippy_lint! {
414 /// **What it does:** Checks for loops which have a range bound that is a mutable variable
416 /// **Why is this bad?** One might think that modifying the mutable variable changes the loop bounds
418 /// **Known problems:** None
422 /// let mut foo = 42;
423 /// for i in 0..foo {
425 /// println!("{}", i); // prints numbers from 0 to 42, not 0 to 21
430 "for loop over a range where one of the bounds is a mutable variable"
433 declare_clippy_lint! {
434 /// **What it does:** Checks whether variables used within while loop condition
435 /// can be (and are) mutated in the body.
437 /// **Why is this bad?** If the condition is unchanged, entering the body of the loop
438 /// will lead to an infinite loop.
440 /// **Known problems:** If the `while`-loop is in a closure, the check for mutation of the
441 /// condition variables in the body can cause false negatives. For example when only `Upvar` `a` is
442 /// in the condition and only `Upvar` `b` gets mutated in the body, the lint will not trigger.
448 /// println!("let me loop forever!");
451 pub WHILE_IMMUTABLE_CONDITION,
453 "variables used within while expression are not mutated in the body"
456 declare_lint_pass!(Loops => [
460 EXPLICIT_INTO_ITER_LOOP,
462 FOR_LOOP_OVER_RESULT,
463 FOR_LOOP_OVER_OPTION,
467 EXPLICIT_COUNTER_LOOP,
469 WHILE_LET_ON_ITERATOR,
473 WHILE_IMMUTABLE_CONDITION,
476 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Loops {
477 #[allow(clippy::too_many_lines)]
478 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
479 if let Some((pat, arg, body)) = higher::for_loop(expr) {
480 // we don't want to check expanded macros
481 // this check is not at the top of the function
482 // since higher::for_loop expressions are marked as expansions
483 if body.span.from_expansion() {
486 check_for_loop(cx, pat, arg, body, expr);
489 // we don't want to check expanded macros
490 if expr.span.from_expansion() {
494 // check for never_loop
495 if let ExprKind::Loop(ref block, _, _) = expr.kind {
496 match never_loop_block(block, expr.hir_id) {
497 NeverLoopResult::AlwaysBreak => span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops"),
498 NeverLoopResult::MayContinueMainLoop | NeverLoopResult::Otherwise => (),
502 // check for `loop { if let {} else break }` that could be `while let`
503 // (also matches an explicit "match" instead of "if let")
504 // (even if the "match" or "if let" is used for declaration)
505 if let ExprKind::Loop(ref block, _, LoopSource::Loop) = expr.kind {
506 // also check for empty `loop {}` statements
507 if block.stmts.is_empty() && block.expr.is_none() && !is_no_std_crate(cx.tcx.hir().krate()) {
512 "empty `loop {}` detected. You may want to either use `panic!()` or add \
513 `std::thread::sleep(..);` to the loop body.",
517 // extract the expression from the first statement (if any) in a block
518 let inner_stmt_expr = extract_expr_from_first_stmt(block);
519 // or extract the first expression (if any) from the block
520 if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
521 if let ExprKind::Match(ref matchexpr, ref arms, ref source) = inner.kind {
522 // ensure "if let" compatible match structure
524 MatchSource::Normal | MatchSource::IfLetDesugar { .. } => {
526 && arms[0].guard.is_none()
527 && arms[1].guard.is_none()
528 && is_simple_break_expr(&arms[1].body)
530 if in_external_macro(cx.sess(), expr.span) {
534 // NOTE: we used to build a body here instead of using
535 // ellipsis, this was removed because:
536 // 1) it was ugly with big bodies;
537 // 2) it was not indented properly;
538 // 3) it wasn’t very smart (see #675).
539 let mut applicability = Applicability::HasPlaceholders;
544 "this loop could be written as a `while let` loop",
547 "while let {} = {} {{ .. }}",
548 snippet_with_applicability(cx, arms[0].pat.span, "..", &mut applicability),
549 snippet_with_applicability(cx, matchexpr.span, "..", &mut applicability),
560 if let ExprKind::Match(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.kind {
561 let pat = &arms[0].pat.kind;
563 &PatKind::TupleStruct(ref qpath, ref pat_args, _),
564 &ExprKind::MethodCall(ref method_path, _, ref method_args),
565 ) = (pat, &match_expr.kind)
567 let iter_expr = &method_args[0];
569 // Don't lint when the iterator is recreated on every iteration
571 if let ExprKind::MethodCall(..) | ExprKind::Call(..) = iter_expr.kind;
572 if let Some(iter_def_id) = get_trait_def_id(cx, &paths::ITERATOR);
573 if implements_trait(cx, cx.tables.expr_ty(iter_expr), iter_def_id, &[]);
579 let lhs_constructor = last_path_segment(qpath);
580 if method_path.ident.name == sym!(next)
581 && match_trait_method(cx, match_expr, &paths::ITERATOR)
582 && lhs_constructor.ident.name == sym!(Some)
583 && (pat_args.is_empty()
584 || !is_refutable(cx, &pat_args[0])
585 && !is_used_inside(cx, iter_expr, &arms[0].body)
586 && !is_iterator_used_after_while_let(cx, iter_expr)
587 && !is_nested(cx, expr, &method_args[0]))
589 let mut applicability = Applicability::MachineApplicable;
590 let iterator = snippet_with_applicability(cx, method_args[0].span, "_", &mut applicability);
591 let loop_var = if pat_args.is_empty() {
594 snippet_with_applicability(cx, pat_args[0].span, "_", &mut applicability).into_owned()
598 WHILE_LET_ON_ITERATOR,
599 expr.span.with_hi(match_expr.span.hi()),
600 "this loop could be written as a `for` loop",
602 format!("for {} in {}", loop_var, iterator),
609 if let Some((cond, body)) = higher::while_loop(&expr) {
610 check_infinite_loop(cx, cond, body);
613 check_needless_collect(expr, cx);
617 enum NeverLoopResult {
618 // A break/return always get triggered but not necessarily for the main loop.
620 // A continue may occur for the main loop.
626 fn absorb_break(arg: &NeverLoopResult) -> NeverLoopResult {
628 NeverLoopResult::AlwaysBreak | NeverLoopResult::Otherwise => NeverLoopResult::Otherwise,
629 NeverLoopResult::MayContinueMainLoop => NeverLoopResult::MayContinueMainLoop,
633 // Combine two results for parts that are called in order.
635 fn combine_seq(first: NeverLoopResult, second: NeverLoopResult) -> NeverLoopResult {
637 NeverLoopResult::AlwaysBreak | NeverLoopResult::MayContinueMainLoop => first,
638 NeverLoopResult::Otherwise => second,
642 // Combine two results where both parts are called but not necessarily in order.
644 fn combine_both(left: NeverLoopResult, right: NeverLoopResult) -> NeverLoopResult {
645 match (left, right) {
646 (NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) => {
647 NeverLoopResult::MayContinueMainLoop
649 (NeverLoopResult::AlwaysBreak, _) | (_, NeverLoopResult::AlwaysBreak) => NeverLoopResult::AlwaysBreak,
650 (NeverLoopResult::Otherwise, NeverLoopResult::Otherwise) => NeverLoopResult::Otherwise,
654 // Combine two results where only one of the part may have been executed.
656 fn combine_branches(b1: NeverLoopResult, b2: NeverLoopResult) -> NeverLoopResult {
658 (NeverLoopResult::AlwaysBreak, NeverLoopResult::AlwaysBreak) => NeverLoopResult::AlwaysBreak,
659 (NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) => {
660 NeverLoopResult::MayContinueMainLoop
662 (NeverLoopResult::Otherwise, _) | (_, NeverLoopResult::Otherwise) => NeverLoopResult::Otherwise,
666 fn never_loop_block(block: &Block<'_>, main_loop_id: HirId) -> NeverLoopResult {
667 let stmts = block.stmts.iter().map(stmt_to_expr);
668 let expr = once(block.expr.as_deref());
669 let mut iter = stmts.chain(expr).filter_map(|e| e);
670 never_loop_expr_seq(&mut iter, main_loop_id)
673 fn stmt_to_expr<'tcx>(stmt: &Stmt<'tcx>) -> Option<&'tcx Expr<'tcx>> {
675 StmtKind::Semi(ref e, ..) | StmtKind::Expr(ref e, ..) => Some(e),
676 StmtKind::Local(ref local) => local.init.as_deref(),
681 fn never_loop_expr(expr: &Expr<'_>, main_loop_id: HirId) -> NeverLoopResult {
684 | ExprKind::Unary(_, ref e)
685 | ExprKind::Cast(ref e, _)
686 | ExprKind::Type(ref e, _)
687 | ExprKind::Field(ref e, _)
688 | ExprKind::AddrOf(_, _, ref e)
689 | ExprKind::Struct(_, _, Some(ref e))
690 | ExprKind::Repeat(ref e, _)
691 | ExprKind::DropTemps(ref e) => never_loop_expr(e, main_loop_id),
692 ExprKind::Array(ref es) | ExprKind::MethodCall(_, _, ref es) | ExprKind::Tup(ref es) => {
693 never_loop_expr_all(&mut es.iter(), main_loop_id)
695 ExprKind::Call(ref e, ref es) => never_loop_expr_all(&mut once(&**e).chain(es.iter()), main_loop_id),
696 ExprKind::Binary(_, ref e1, ref e2)
697 | ExprKind::Assign(ref e1, ref e2, _)
698 | ExprKind::AssignOp(_, ref e1, ref e2)
699 | ExprKind::Index(ref e1, ref e2) => never_loop_expr_all(&mut [&**e1, &**e2].iter().cloned(), main_loop_id),
700 ExprKind::Loop(ref b, _, _) => {
701 // Break can come from the inner loop so remove them.
702 absorb_break(&never_loop_block(b, main_loop_id))
704 ExprKind::Match(ref e, ref arms, _) => {
705 let e = never_loop_expr(e, main_loop_id);
709 let arms = never_loop_expr_branch(&mut arms.iter().map(|a| &*a.body), main_loop_id);
713 ExprKind::Block(ref b, _) => never_loop_block(b, main_loop_id),
714 ExprKind::Continue(d) => {
717 .expect("target ID can only be missing in the presence of compilation errors");
718 if id == main_loop_id {
719 NeverLoopResult::MayContinueMainLoop
721 NeverLoopResult::AlwaysBreak
724 ExprKind::Break(_, ref e) | ExprKind::Ret(ref e) => {
725 if let Some(ref e) = *e {
726 combine_seq(never_loop_expr(e, main_loop_id), NeverLoopResult::AlwaysBreak)
728 NeverLoopResult::AlwaysBreak
731 ExprKind::Struct(_, _, None)
732 | ExprKind::Yield(_, _)
733 | ExprKind::Closure(_, _, _, _, _)
734 | ExprKind::LlvmInlineAsm(_)
737 | ExprKind::Err => NeverLoopResult::Otherwise,
741 fn never_loop_expr_seq<'a, T: Iterator<Item = &'a Expr<'a>>>(es: &mut T, main_loop_id: HirId) -> NeverLoopResult {
742 es.map(|e| never_loop_expr(e, main_loop_id))
743 .fold(NeverLoopResult::Otherwise, combine_seq)
746 fn never_loop_expr_all<'a, T: Iterator<Item = &'a Expr<'a>>>(es: &mut T, main_loop_id: HirId) -> NeverLoopResult {
747 es.map(|e| never_loop_expr(e, main_loop_id))
748 .fold(NeverLoopResult::Otherwise, combine_both)
751 fn never_loop_expr_branch<'a, T: Iterator<Item = &'a Expr<'a>>>(e: &mut T, main_loop_id: HirId) -> NeverLoopResult {
752 e.map(|e| never_loop_expr(e, main_loop_id))
753 .fold(NeverLoopResult::AlwaysBreak, combine_branches)
756 fn check_for_loop<'a, 'tcx>(
757 cx: &LateContext<'a, 'tcx>,
760 body: &'tcx Expr<'_>,
761 expr: &'tcx Expr<'_>,
763 check_for_loop_range(cx, pat, arg, body, expr);
764 check_for_loop_reverse_range(cx, arg, expr);
765 check_for_loop_arg(cx, pat, arg, expr);
766 check_for_loop_explicit_counter(cx, pat, arg, body, expr);
767 check_for_loop_over_map_kv(cx, pat, arg, body, expr);
768 check_for_mut_range_bound(cx, arg, body);
769 detect_manual_memcpy(cx, pat, arg, body, expr);
772 fn same_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr<'_>, var: HirId) -> bool {
774 if let ExprKind::Path(qpath) = &expr.kind;
775 if let QPath::Resolved(None, path) = qpath;
776 if path.segments.len() == 1;
777 if let Res::Local(local_id) = qpath_res(cx, qpath, expr.hir_id);
788 #[derive(Clone, Copy)]
800 fn negative(value: String) -> Self {
803 sign: OffsetSign::Negative,
807 fn positive(value: String) -> Self {
810 sign: OffsetSign::Positive,
815 struct FixedOffsetVar<'hir> {
816 var: &'hir Expr<'hir>,
820 fn is_slice_like<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'_>) -> bool {
821 let is_slice = match ty.kind {
822 ty::Ref(_, subty, _) => is_slice_like(cx, subty),
823 ty::Slice(..) | ty::Array(..) => true,
827 is_slice || is_type_diagnostic_item(cx, ty, sym!(vec_type)) || is_type_diagnostic_item(cx, ty, sym!(vecdeque_type))
830 fn fetch_cloned_expr<'tcx>(expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
832 if let ExprKind::MethodCall(method, _, args) = expr.kind;
833 if method.ident.name == sym!(clone);
835 if let Some(arg) = args.get(0);
836 then { arg } else { expr }
840 fn get_offset<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, idx: &Expr<'_>, var: HirId) -> Option<Offset> {
841 fn extract_offset<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &Expr<'_>, var: HirId) -> Option<String> {
843 ExprKind::Lit(l) => match l.node {
844 ast::LitKind::Int(x, _ty) => Some(x.to_string()),
847 ExprKind::Path(..) if !same_var(cx, e, var) => Some(snippet_opt(cx, e.span).unwrap_or_else(|| "??".into())),
853 ExprKind::Binary(op, lhs, rhs) => match op.node {
855 let offset_opt = if same_var(cx, lhs, var) {
856 extract_offset(cx, rhs, var)
857 } else if same_var(cx, rhs, var) {
858 extract_offset(cx, lhs, var)
863 offset_opt.map(Offset::positive)
865 BinOpKind::Sub if same_var(cx, lhs, var) => extract_offset(cx, rhs, var).map(Offset::negative),
868 ExprKind::Path(..) if same_var(cx, idx, var) => Some(Offset::positive("0".into())),
873 fn get_assignments<'a, 'tcx>(
874 body: &'tcx Expr<'tcx>,
875 ) -> impl Iterator<Item = Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)>> {
876 fn get_assignment<'a, 'tcx>(e: &'tcx Expr<'tcx>) -> Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)> {
877 if let ExprKind::Assign(lhs, rhs, _) = e.kind {
884 // This is one of few ways to return different iterators
885 // derived from: https://stackoverflow.com/questions/29760668/conditionally-iterate-over-one-of-several-possible-iterators/52064434#52064434
886 let mut iter_a = None;
887 let mut iter_b = None;
889 if let ExprKind::Block(b, _) = body.kind {
890 let Block { stmts, expr, .. } = *b;
894 .filter_map(|stmt| match stmt.kind {
895 StmtKind::Local(..) | StmtKind::Item(..) => None,
896 StmtKind::Expr(e) | StmtKind::Semi(e) => Some(e),
898 .chain(expr.into_iter())
902 iter_b = Some(get_assignment(body))
905 iter_a.into_iter().flatten().chain(iter_b.into_iter())
908 fn build_manual_memcpy_suggestion<'a, 'tcx>(
909 cx: &LateContext<'a, 'tcx>,
912 limits: ast::RangeLimits,
913 dst_var: FixedOffsetVar<'_>,
914 src_var: FixedOffsetVar<'_>,
916 fn print_sum(arg1: &str, arg2: &Offset) -> String {
917 match (arg1, &arg2.value[..], arg2.sign) {
918 ("0", "0", _) => "0".into(),
919 ("0", x, OffsetSign::Positive) | (x, "0", _) => x.into(),
920 ("0", x, OffsetSign::Negative) => format!("-{}", x),
921 (x, y, OffsetSign::Positive) => format!("({} + {})", x, y),
922 (x, y, OffsetSign::Negative) => {
926 format!("({} - {})", x, y)
932 fn print_offset(start_str: &str, inline_offset: &Offset) -> String {
933 let offset = print_sum(start_str, inline_offset);
934 if offset.as_str() == "0" {
941 let print_limit = |end: &Expr<'_>, offset: Offset, var: &Expr<'_>| {
943 if let ExprKind::MethodCall(method, _, len_args) = end.kind;
944 if method.ident.name == sym!(len);
945 if len_args.len() == 1;
946 if let Some(arg) = len_args.get(0);
947 if var_def_id(cx, arg) == var_def_id(cx, var);
950 OffsetSign::Negative => format!("({} - {})", snippet(cx, end.span, "<src>.len()"), offset.value),
951 OffsetSign::Positive => "".into(),
954 let end_str = match limits {
955 ast::RangeLimits::Closed => {
956 let end = sugg::Sugg::hir(cx, end, "<count>");
957 format!("{}", end + sugg::ONE)
959 ast::RangeLimits::HalfOpen => format!("{}", snippet(cx, end.span, "..")),
962 print_sum(&end_str, &offset)
967 let start_str = snippet(cx, start.span, "").to_string();
968 let dst_offset = print_offset(&start_str, &dst_var.offset);
969 let dst_limit = print_limit(end, dst_var.offset, dst_var.var);
970 let src_offset = print_offset(&start_str, &src_var.offset);
971 let src_limit = print_limit(end, src_var.offset, src_var.var);
973 let dst_var_name = snippet_opt(cx, dst_var.var.span).unwrap_or_else(|| "???".into());
974 let src_var_name = snippet_opt(cx, src_var.var.span).unwrap_or_else(|| "???".into());
976 let dst = if dst_offset == "" && dst_limit == "" {
979 format!("{}[{}..{}]", dst_var_name, dst_offset, dst_limit)
983 "{}.clone_from_slice(&{}[{}..{}])",
984 dst, src_var_name, src_offset, src_limit
987 /// Checks for for loops that sequentially copy items from one slice-like
988 /// object to another.
989 fn detect_manual_memcpy<'a, 'tcx>(
990 cx: &LateContext<'a, 'tcx>,
993 body: &'tcx Expr<'_>,
994 expr: &'tcx Expr<'_>,
996 if let Some(higher::Range {
1000 }) = higher::range(cx, arg)
1002 // the var must be a single name
1003 if let PatKind::Binding(_, canonical_id, _, _) = pat.kind {
1004 // The only statements in the for loops can be indexed assignments from
1005 // indexed retrievals.
1006 let big_sugg = get_assignments(body)
1008 o.and_then(|(lhs, rhs)| {
1009 let rhs = fetch_cloned_expr(rhs);
1011 if let ExprKind::Index(seqexpr_left, idx_left) = lhs.kind;
1012 if let ExprKind::Index(seqexpr_right, idx_right) = rhs.kind;
1013 if is_slice_like(cx, cx.tables.expr_ty(seqexpr_left))
1014 && is_slice_like(cx, cx.tables.expr_ty(seqexpr_right));
1015 if let Some(offset_left) = get_offset(cx, &idx_left, canonical_id);
1016 if let Some(offset_right) = get_offset(cx, &idx_right, canonical_id);
1018 // Source and destination must be different
1019 if var_def_id(cx, seqexpr_left) != var_def_id(cx, seqexpr_right);
1021 Some((FixedOffsetVar { var: seqexpr_left, offset: offset_left },
1022 FixedOffsetVar { var: seqexpr_right, offset: offset_right }))
1029 .map(|o| o.map(|(dst, src)| build_manual_memcpy_suggestion(cx, start, end, limits, dst, src)))
1030 .collect::<Option<Vec<_>>>()
1031 .filter(|v| !v.is_empty())
1032 .map(|v| v.join("\n "));
1034 if let Some(big_sugg) = big_sugg {
1039 "it looks like you're manually copying between slices",
1040 "try replacing the loop by",
1042 Applicability::Unspecified,
1049 /// Checks for looping over a range and then indexing a sequence with it.
1050 /// The iteratee must be a range literal.
1051 #[allow(clippy::too_many_lines)]
1052 fn check_for_loop_range<'a, 'tcx>(
1053 cx: &LateContext<'a, 'tcx>,
1055 arg: &'tcx Expr<'_>,
1056 body: &'tcx Expr<'_>,
1057 expr: &'tcx Expr<'_>,
1059 if let Some(higher::Range {
1063 }) = higher::range(cx, arg)
1065 // the var must be a single name
1066 if let PatKind::Binding(_, canonical_id, ident, _) = pat.kind {
1067 let mut visitor = VarVisitor {
1070 indexed_mut: FxHashSet::default(),
1071 indexed_indirectly: FxHashMap::default(),
1072 indexed_directly: FxHashMap::default(),
1073 referenced: FxHashSet::default(),
1075 prefer_mutable: false,
1077 walk_expr(&mut visitor, body);
1079 // linting condition: we only indexed one variable, and indexed it directly
1080 if visitor.indexed_indirectly.is_empty() && visitor.indexed_directly.len() == 1 {
1081 let (indexed, (indexed_extent, indexed_ty)) = visitor
1085 .expect("already checked that we have exactly 1 element");
1087 // ensure that the indexed variable was declared before the loop, see #601
1088 if let Some(indexed_extent) = indexed_extent {
1089 let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
1090 let parent_def_id = cx.tcx.hir().local_def_id(parent_id);
1091 let region_scope_tree = cx.tcx.region_scope_tree(parent_def_id);
1092 let pat_extent = region_scope_tree.var_scope(pat.hir_id.local_id);
1093 if region_scope_tree.is_subscope_of(indexed_extent, pat_extent) {
1098 // don't lint if the container that is indexed does not have .iter() method
1099 let has_iter = has_iter_method(cx, indexed_ty);
1100 if has_iter.is_none() {
1104 // don't lint if the container that is indexed into is also used without
1106 if visitor.referenced.contains(&indexed) {
1110 let starts_at_zero = is_integer_const(cx, start, 0);
1112 let skip = if starts_at_zero {
1115 format!(".skip({})", snippet(cx, start.span, ".."))
1118 let mut end_is_start_plus_val = false;
1120 let take = if let Some(end) = *end {
1121 let mut take_expr = end;
1123 if let ExprKind::Binary(ref op, ref left, ref right) = end.kind {
1124 if let BinOpKind::Add = op.node {
1125 let start_equal_left = SpanlessEq::new(cx).eq_expr(start, left);
1126 let start_equal_right = SpanlessEq::new(cx).eq_expr(start, right);
1128 if start_equal_left {
1130 } else if start_equal_right {
1134 end_is_start_plus_val = start_equal_left | start_equal_right;
1138 if is_len_call(end, indexed) || is_end_eq_array_len(cx, end, limits, indexed_ty) {
1142 ast::RangeLimits::Closed => {
1143 let take_expr = sugg::Sugg::hir(cx, take_expr, "<count>");
1144 format!(".take({})", take_expr + sugg::ONE)
1146 ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, take_expr.span, "..")),
1153 let (ref_mut, method) = if visitor.indexed_mut.contains(&indexed) {
1154 ("mut ", "iter_mut")
1159 let take_is_empty = take.is_empty();
1160 let mut method_1 = take;
1161 let mut method_2 = skip;
1163 if end_is_start_plus_val {
1164 mem::swap(&mut method_1, &mut method_2);
1167 if visitor.nonindex {
1170 NEEDLESS_RANGE_LOOP,
1172 &format!("the loop variable `{}` is used to index `{}`", ident.name, indexed),
1176 "consider using an iterator".to_string(),
1178 (pat.span, format!("({}, <item>)", ident.name)),
1181 format!("{}.{}().enumerate(){}{}", indexed, method, method_1, method_2),
1188 let repl = if starts_at_zero && take_is_empty {
1189 format!("&{}{}", ref_mut, indexed)
1191 format!("{}.{}(){}{}", indexed, method, method_1, method_2)
1196 NEEDLESS_RANGE_LOOP,
1199 "the loop variable `{}` is only used to index `{}`.",
1205 "consider using an iterator".to_string(),
1206 vec![(pat.span, "<item>".to_string()), (arg.span, repl)],
1216 fn is_len_call(expr: &Expr<'_>, var: Name) -> bool {
1218 if let ExprKind::MethodCall(ref method, _, ref len_args) = expr.kind;
1219 if len_args.len() == 1;
1220 if method.ident.name == sym!(len);
1221 if let ExprKind::Path(QPath::Resolved(_, ref path)) = len_args[0].kind;
1222 if path.segments.len() == 1;
1223 if path.segments[0].ident.name == var;
1232 fn is_end_eq_array_len<'tcx>(
1233 cx: &LateContext<'_, 'tcx>,
1235 limits: ast::RangeLimits,
1236 indexed_ty: Ty<'tcx>,
1239 if let ExprKind::Lit(ref lit) = end.kind;
1240 if let ast::LitKind::Int(end_int, _) = lit.node;
1241 if let ty::Array(_, arr_len_const) = indexed_ty.kind;
1242 if let Some(arr_len) = arr_len_const.try_eval_usize(cx.tcx, cx.param_env);
1244 return match limits {
1245 ast::RangeLimits::Closed => end_int + 1 >= arr_len.into(),
1246 ast::RangeLimits::HalfOpen => end_int >= arr_len.into(),
1254 fn check_for_loop_reverse_range<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arg: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) {
1255 // if this for loop is iterating over a two-sided range...
1256 if let Some(higher::Range {
1260 }) = higher::range(cx, arg)
1262 // ...and both sides are compile-time constant integers...
1263 if let Some((start_idx, _)) = constant(cx, cx.tables, start) {
1264 if let Some((end_idx, _)) = constant(cx, cx.tables, end) {
1265 // ...and the start index is greater than the end index,
1266 // this loop will never run. This is often confusing for developers
1267 // who think that this will iterate from the larger value to the
1269 let ty = cx.tables.expr_ty(start);
1270 let (sup, eq) = match (start_idx, end_idx) {
1271 (Constant::Int(start_idx), Constant::Int(end_idx)) => (
1273 ty::Int(ity) => sext(cx.tcx, start_idx, ity) > sext(cx.tcx, end_idx, ity),
1274 ty::Uint(_) => start_idx > end_idx,
1277 start_idx == end_idx,
1279 _ => (false, false),
1283 let start_snippet = snippet(cx, start.span, "_");
1284 let end_snippet = snippet(cx, end.span, "_");
1285 let dots = if limits == ast::RangeLimits::Closed {
1295 "this range is empty so this for loop will never run",
1297 diag.span_suggestion(
1299 "consider using the following if you are attempting to iterate over this \
1302 "({end}{dots}{start}).rev()",
1305 start = start_snippet
1307 Applicability::MaybeIncorrect,
1311 } else if eq && limits != ast::RangeLimits::Closed {
1312 // if they are equal, it's also problematic - this loop
1318 "this range is empty so this for loop will never run",
1326 fn lint_iter_method(cx: &LateContext<'_, '_>, args: &[Expr<'_>], arg: &Expr<'_>, method_name: &str) {
1327 let mut applicability = Applicability::MachineApplicable;
1328 let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability);
1329 let muta = if method_name == "iter_mut" { "mut " } else { "" };
1334 "it is more concise to loop over references to containers instead of using explicit \
1336 "to write this more concisely, try",
1337 format!("&{}{}", muta, object),
1342 fn check_for_loop_arg(cx: &LateContext<'_, '_>, pat: &Pat<'_>, arg: &Expr<'_>, expr: &Expr<'_>) {
1343 let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
1344 if let ExprKind::MethodCall(ref method, _, ref args) = arg.kind {
1345 // just the receiver, no arguments
1346 if args.len() == 1 {
1347 let method_name = &*method.ident.as_str();
1348 // check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
1349 if method_name == "iter" || method_name == "iter_mut" {
1350 if is_ref_iterable_type(cx, &args[0]) {
1351 lint_iter_method(cx, args, arg, method_name);
1353 } else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
1354 let receiver_ty = cx.tables.expr_ty(&args[0]);
1355 let receiver_ty_adjusted = cx.tables.expr_ty_adjusted(&args[0]);
1356 if same_tys(cx, receiver_ty, receiver_ty_adjusted) {
1357 let mut applicability = Applicability::MachineApplicable;
1358 let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability);
1361 EXPLICIT_INTO_ITER_LOOP,
1363 "it is more concise to loop over containers instead of using explicit \
1365 "to write this more concisely, try",
1370 let ref_receiver_ty = cx.tcx.mk_ref(
1371 cx.tcx.lifetimes.re_erased,
1374 mutbl: Mutability::Not,
1377 if same_tys(cx, receiver_ty_adjusted, ref_receiver_ty) {
1378 lint_iter_method(cx, args, arg, method_name)
1381 } else if method_name == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
1386 "you are iterating over `Iterator::next()` which is an Option; this will compile but is \
1387 probably not what you want",
1389 next_loop_linted = true;
1393 if !next_loop_linted {
1394 check_arg_type(cx, pat, arg);
1398 /// Checks for `for` loops over `Option`s and `Result`s.
1399 fn check_arg_type(cx: &LateContext<'_, '_>, pat: &Pat<'_>, arg: &Expr<'_>) {
1400 let ty = cx.tables.expr_ty(arg);
1401 if is_type_diagnostic_item(cx, ty, sym!(option_type)) {
1404 FOR_LOOP_OVER_OPTION,
1407 "for loop over `{0}`, which is an `Option`. This is more readably written as an \
1408 `if let` statement.",
1409 snippet(cx, arg.span, "_")
1413 "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
1414 snippet(cx, pat.span, "_"),
1415 snippet(cx, arg.span, "_")
1418 } else if is_type_diagnostic_item(cx, ty, sym!(result_type)) {
1421 FOR_LOOP_OVER_RESULT,
1424 "for loop over `{0}`, which is a `Result`. This is more readably written as an \
1425 `if let` statement.",
1426 snippet(cx, arg.span, "_")
1430 "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
1431 snippet(cx, pat.span, "_"),
1432 snippet(cx, arg.span, "_")
1438 fn check_for_loop_explicit_counter<'a, 'tcx>(
1439 cx: &LateContext<'a, 'tcx>,
1441 arg: &'tcx Expr<'_>,
1442 body: &'tcx Expr<'_>,
1443 expr: &'tcx Expr<'_>,
1445 // Look for variables that are incremented once per loop iteration.
1446 let mut visitor = IncrementVisitor {
1448 states: FxHashMap::default(),
1452 walk_expr(&mut visitor, body);
1454 // For each candidate, check the parent block to see if
1455 // it's initialized to zero at the start of the loop.
1456 if let Some(block) = get_enclosing_block(&cx, expr.hir_id) {
1457 for (id, _) in visitor.states.iter().filter(|&(_, v)| *v == VarState::IncrOnce) {
1458 let mut visitor2 = InitializeVisitor {
1462 state: VarState::IncrOnce,
1467 walk_block(&mut visitor2, block);
1469 if visitor2.state == VarState::Warn {
1470 if let Some(name) = visitor2.name {
1471 let mut applicability = Applicability::MachineApplicable;
1473 // for some reason this is the only way to get the `Span`
1474 // of the entire `for` loop
1475 let for_span = if let ExprKind::Match(_, arms, _) = &expr.kind {
1483 EXPLICIT_COUNTER_LOOP,
1484 for_span.with_hi(arg.span.hi()),
1485 &format!("the variable `{}` is used as a loop counter.", name),
1488 "for ({}, {}) in {}.enumerate()",
1490 snippet_with_applicability(cx, pat.span, "item", &mut applicability),
1491 make_iterator_snippet(cx, arg, &mut applicability),
1501 /// If `arg` was the argument to a `for` loop, return the "cleanest" way of writing the
1502 /// actual `Iterator` that the loop uses.
1503 fn make_iterator_snippet(cx: &LateContext<'_, '_>, arg: &Expr<'_>, applic_ref: &mut Applicability) -> String {
1504 let impls_iterator = get_trait_def_id(cx, &paths::ITERATOR)
1505 .map_or(false, |id| implements_trait(cx, cx.tables.expr_ty(arg), id, &[]));
1509 sugg::Sugg::hir_with_applicability(cx, arg, "_", applic_ref).maybe_par()
1512 // (&x).into_iter() ==> x.iter()
1513 // (&mut x).into_iter() ==> x.iter_mut()
1515 ExprKind::AddrOf(BorrowKind::Ref, mutability, arg_inner)
1516 if has_iter_method(cx, cx.tables.expr_ty(&arg_inner)).is_some() =>
1518 let meth_name = match mutability {
1519 Mutability::Mut => "iter_mut",
1520 Mutability::Not => "iter",
1524 sugg::Sugg::hir_with_applicability(cx, &arg_inner, "_", applic_ref).maybe_par(),
1530 sugg::Sugg::hir_with_applicability(cx, arg, "_", applic_ref).maybe_par()
1536 /// Checks for the `FOR_KV_MAP` lint.
1537 fn check_for_loop_over_map_kv<'a, 'tcx>(
1538 cx: &LateContext<'a, 'tcx>,
1540 arg: &'tcx Expr<'_>,
1541 body: &'tcx Expr<'_>,
1542 expr: &'tcx Expr<'_>,
1544 let pat_span = pat.span;
1546 if let PatKind::Tuple(ref pat, _) = pat.kind {
1548 let arg_span = arg.span;
1549 let (new_pat_span, kind, ty, mutbl) = match cx.tables.expr_ty(arg).kind {
1550 ty::Ref(_, ty, mutbl) => match (&pat[0].kind, &pat[1].kind) {
1551 (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", ty, mutbl),
1552 (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", ty, Mutability::Not),
1557 let mutbl = match mutbl {
1558 Mutability::Not => "",
1559 Mutability::Mut => "_mut",
1561 let arg = match arg.kind {
1562 ExprKind::AddrOf(BorrowKind::Ref, _, ref expr) => &**expr,
1566 if is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) || match_type(cx, ty, &paths::BTREEMAP) {
1571 &format!("you seem to want to iterate on a map's {}s", kind),
1573 let map = sugg::Sugg::hir(cx, arg, "map");
1576 "use the corresponding method".into(),
1578 (pat_span, snippet(cx, new_pat_span, kind).into_owned()),
1579 (arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)),
1589 struct MutatePairDelegate {
1590 hir_id_low: Option<HirId>,
1591 hir_id_high: Option<HirId>,
1592 span_low: Option<Span>,
1593 span_high: Option<Span>,
1596 impl<'tcx> Delegate<'tcx> for MutatePairDelegate {
1597 fn consume(&mut self, _: &Place<'tcx>, _: ConsumeMode) {}
1599 fn borrow(&mut self, cmt: &Place<'tcx>, bk: ty::BorrowKind) {
1600 if let ty::BorrowKind::MutBorrow = bk {
1601 if let PlaceBase::Local(id) = cmt.base {
1602 if Some(id) == self.hir_id_low {
1603 self.span_low = Some(cmt.span)
1605 if Some(id) == self.hir_id_high {
1606 self.span_high = Some(cmt.span)
1612 fn mutate(&mut self, cmt: &Place<'tcx>) {
1613 if let PlaceBase::Local(id) = cmt.base {
1614 if Some(id) == self.hir_id_low {
1615 self.span_low = Some(cmt.span)
1617 if Some(id) == self.hir_id_high {
1618 self.span_high = Some(cmt.span)
1624 impl<'tcx> MutatePairDelegate {
1625 fn mutation_span(&self) -> (Option<Span>, Option<Span>) {
1626 (self.span_low, self.span_high)
1630 fn check_for_mut_range_bound(cx: &LateContext<'_, '_>, arg: &Expr<'_>, body: &Expr<'_>) {
1631 if let Some(higher::Range {
1635 }) = higher::range(cx, arg)
1637 let mut_ids = vec![check_for_mutability(cx, start), check_for_mutability(cx, end)];
1638 if mut_ids[0].is_some() || mut_ids[1].is_some() {
1639 let (span_low, span_high) = check_for_mutation(cx, body, &mut_ids);
1640 mut_warn_with_span(cx, span_low);
1641 mut_warn_with_span(cx, span_high);
1646 fn mut_warn_with_span(cx: &LateContext<'_, '_>, span: Option<Span>) {
1647 if let Some(sp) = span {
1652 "attempt to mutate range bound within loop; note that the range of the loop is unchanged",
1657 fn check_for_mutability(cx: &LateContext<'_, '_>, bound: &Expr<'_>) -> Option<HirId> {
1659 if let ExprKind::Path(ref qpath) = bound.kind;
1660 if let QPath::Resolved(None, _) = *qpath;
1662 let res = qpath_res(cx, qpath, bound.hir_id);
1663 if let Res::Local(hir_id) = res {
1664 let node_str = cx.tcx.hir().get(hir_id);
1666 if let Node::Binding(pat) = node_str;
1667 if let PatKind::Binding(bind_ann, ..) = pat.kind;
1668 if let BindingAnnotation::Mutable = bind_ann;
1670 return Some(hir_id);
1679 fn check_for_mutation(
1680 cx: &LateContext<'_, '_>,
1682 bound_ids: &[Option<HirId>],
1683 ) -> (Option<Span>, Option<Span>) {
1684 let mut delegate = MutatePairDelegate {
1685 hir_id_low: bound_ids[0],
1686 hir_id_high: bound_ids[1],
1690 let def_id = body.hir_id.owner.to_def_id();
1691 cx.tcx.infer_ctxt().enter(|infcx| {
1692 ExprUseVisitor::new(&mut delegate, &infcx, def_id, cx.param_env, cx.tables).walk_expr(body);
1694 delegate.mutation_span()
1697 /// Returns `true` if the pattern is a `PatWild` or an ident prefixed with `_`.
1698 fn pat_is_wild<'tcx>(pat: &'tcx PatKind<'_>, body: &'tcx Expr<'_>) -> bool {
1700 PatKind::Wild => true,
1701 PatKind::Binding(.., ident, None) if ident.as_str().starts_with('_') => is_unused(&ident, body),
1706 struct LocalUsedVisitor<'a, 'tcx> {
1707 cx: &'a LateContext<'a, 'tcx>,
1712 impl<'a, 'tcx> Visitor<'tcx> for LocalUsedVisitor<'a, 'tcx> {
1713 type Map = Map<'tcx>;
1715 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
1716 if same_var(self.cx, expr, self.local) {
1719 walk_expr(self, expr);
1723 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1724 NestedVisitorMap::None
1728 struct VarVisitor<'a, 'tcx> {
1729 /// context reference
1730 cx: &'a LateContext<'a, 'tcx>,
1731 /// var name to look for as index
1733 /// indexed variables that are used mutably
1734 indexed_mut: FxHashSet<Name>,
1735 /// indirectly indexed variables (`v[(i + 4) % N]`), the extend is `None` for global
1736 indexed_indirectly: FxHashMap<Name, Option<region::Scope>>,
1737 /// subset of `indexed` of vars that are indexed directly: `v[i]`
1738 /// this will not contain cases like `v[calc_index(i)]` or `v[(i + 4) % N]`
1739 indexed_directly: FxHashMap<Name, (Option<region::Scope>, Ty<'tcx>)>,
1740 /// Any names that are used outside an index operation.
1741 /// Used to detect things like `&mut vec` used together with `vec[i]`
1742 referenced: FxHashSet<Name>,
1743 /// has the loop variable been used in expressions other than the index of
1746 /// Whether we are inside the `$` in `&mut $` or `$ = foo` or `$.bar`, where bar
1747 /// takes `&mut self`
1748 prefer_mutable: bool,
1751 impl<'a, 'tcx> VarVisitor<'a, 'tcx> {
1752 fn check(&mut self, idx: &'tcx Expr<'_>, seqexpr: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) -> bool {
1754 // the indexed container is referenced by a name
1755 if let ExprKind::Path(ref seqpath) = seqexpr.kind;
1756 if let QPath::Resolved(None, ref seqvar) = *seqpath;
1757 if seqvar.segments.len() == 1;
1759 let index_used_directly = same_var(self.cx, idx, self.var);
1760 let indexed_indirectly = {
1761 let mut used_visitor = LocalUsedVisitor {
1766 walk_expr(&mut used_visitor, idx);
1770 if indexed_indirectly || index_used_directly {
1771 if self.prefer_mutable {
1772 self.indexed_mut.insert(seqvar.segments[0].ident.name);
1774 let res = qpath_res(self.cx, seqpath, seqexpr.hir_id);
1776 Res::Local(hir_id) => {
1777 let parent_id = self.cx.tcx.hir().get_parent_item(expr.hir_id);
1778 let parent_def_id = self.cx.tcx.hir().local_def_id(parent_id);
1779 let extent = self.cx.tcx.region_scope_tree(parent_def_id).var_scope(hir_id.local_id);
1780 if indexed_indirectly {
1781 self.indexed_indirectly.insert(seqvar.segments[0].ident.name, Some(extent));
1783 if index_used_directly {
1784 self.indexed_directly.insert(
1785 seqvar.segments[0].ident.name,
1786 (Some(extent), self.cx.tables.node_type(seqexpr.hir_id)),
1789 return false; // no need to walk further *on the variable*
1791 Res::Def(DefKind::Static | DefKind::Const, ..) => {
1792 if indexed_indirectly {
1793 self.indexed_indirectly.insert(seqvar.segments[0].ident.name, None);
1795 if index_used_directly {
1796 self.indexed_directly.insert(
1797 seqvar.segments[0].ident.name,
1798 (None, self.cx.tables.node_type(seqexpr.hir_id)),
1801 return false; // no need to walk further *on the variable*
1812 impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
1813 type Map = Map<'tcx>;
1815 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
1818 if let ExprKind::MethodCall(ref meth, _, ref args) = expr.kind;
1819 if (meth.ident.name == sym!(index) && match_trait_method(self.cx, expr, &paths::INDEX))
1820 || (meth.ident.name == sym!(index_mut) && match_trait_method(self.cx, expr, &paths::INDEX_MUT));
1821 if !self.check(&args[1], &args[0], expr);
1827 if let ExprKind::Index(ref seqexpr, ref idx) = expr.kind;
1828 if !self.check(idx, seqexpr, expr);
1833 // directly using a variable
1834 if let ExprKind::Path(ref qpath) = expr.kind;
1835 if let QPath::Resolved(None, ref path) = *qpath;
1836 if path.segments.len() == 1;
1838 if let Res::Local(local_id) = qpath_res(self.cx, qpath, expr.hir_id) {
1839 if local_id == self.var {
1840 self.nonindex = true;
1842 // not the correct variable, but still a variable
1843 self.referenced.insert(path.segments[0].ident.name);
1849 let old = self.prefer_mutable;
1851 ExprKind::AssignOp(_, ref lhs, ref rhs) | ExprKind::Assign(ref lhs, ref rhs, _) => {
1852 self.prefer_mutable = true;
1853 self.visit_expr(lhs);
1854 self.prefer_mutable = false;
1855 self.visit_expr(rhs);
1857 ExprKind::AddrOf(BorrowKind::Ref, mutbl, ref expr) => {
1858 if mutbl == Mutability::Mut {
1859 self.prefer_mutable = true;
1861 self.visit_expr(expr);
1863 ExprKind::Call(ref f, args) => {
1866 let ty = self.cx.tables.expr_ty_adjusted(expr);
1867 self.prefer_mutable = false;
1868 if let ty::Ref(_, _, mutbl) = ty.kind {
1869 if mutbl == Mutability::Mut {
1870 self.prefer_mutable = true;
1873 self.visit_expr(expr);
1876 ExprKind::MethodCall(_, _, args) => {
1877 let def_id = self.cx.tables.type_dependent_def_id(expr.hir_id).unwrap();
1878 for (ty, expr) in self.cx.tcx.fn_sig(def_id).inputs().skip_binder().iter().zip(args) {
1879 self.prefer_mutable = false;
1880 if let ty::Ref(_, _, mutbl) = ty.kind {
1881 if mutbl == Mutability::Mut {
1882 self.prefer_mutable = true;
1885 self.visit_expr(expr);
1888 ExprKind::Closure(_, _, body_id, ..) => {
1889 let body = self.cx.tcx.hir().body(body_id);
1890 self.visit_expr(&body.value);
1892 _ => walk_expr(self, expr),
1894 self.prefer_mutable = old;
1896 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1897 NestedVisitorMap::None
1901 fn is_used_inside<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>, container: &'tcx Expr<'_>) -> bool {
1902 let def_id = match var_def_id(cx, expr) {
1904 None => return false,
1906 if let Some(used_mutably) = mutated_variables(container, cx) {
1907 if used_mutably.contains(&def_id) {
1914 fn is_iterator_used_after_while_let<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, iter_expr: &'tcx Expr<'_>) -> bool {
1915 let def_id = match var_def_id(cx, iter_expr) {
1917 None => return false,
1919 let mut visitor = VarUsedAfterLoopVisitor {
1922 iter_expr_id: iter_expr.hir_id,
1923 past_while_let: false,
1924 var_used_after_while_let: false,
1926 if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
1927 walk_block(&mut visitor, enclosing_block);
1929 visitor.var_used_after_while_let
1932 struct VarUsedAfterLoopVisitor<'a, 'tcx> {
1933 cx: &'a LateContext<'a, 'tcx>,
1935 iter_expr_id: HirId,
1936 past_while_let: bool,
1937 var_used_after_while_let: bool,
1940 impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
1941 type Map = Map<'tcx>;
1943 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
1944 if self.past_while_let {
1945 if Some(self.def_id) == var_def_id(self.cx, expr) {
1946 self.var_used_after_while_let = true;
1948 } else if self.iter_expr_id == expr.hir_id {
1949 self.past_while_let = true;
1951 walk_expr(self, expr);
1953 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1954 NestedVisitorMap::None
1958 /// Returns `true` if the type of expr is one that provides `IntoIterator` impls
1959 /// for `&T` and `&mut T`, such as `Vec`.
1961 fn is_ref_iterable_type(cx: &LateContext<'_, '_>, e: &Expr<'_>) -> bool {
1962 // no walk_ptrs_ty: calling iter() on a reference can make sense because it
1963 // will allow further borrows afterwards
1964 let ty = cx.tables.expr_ty(e);
1965 is_iterable_array(ty, cx) ||
1966 is_type_diagnostic_item(cx, ty, sym!(vec_type)) ||
1967 match_type(cx, ty, &paths::LINKED_LIST) ||
1968 is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) ||
1969 is_type_diagnostic_item(cx, ty, sym!(hashset_type)) ||
1970 is_type_diagnostic_item(cx, ty, sym!(vecdeque_type)) ||
1971 match_type(cx, ty, &paths::BINARY_HEAP) ||
1972 match_type(cx, ty, &paths::BTREEMAP) ||
1973 match_type(cx, ty, &paths::BTREESET)
1976 fn is_iterable_array<'tcx>(ty: Ty<'tcx>, cx: &LateContext<'_, 'tcx>) -> bool {
1977 // IntoIterator is currently only implemented for array sizes <= 32 in rustc
1979 ty::Array(_, n) => {
1980 if let Some(val) = n.try_eval_usize(cx.tcx, cx.param_env) {
1981 (0..=32).contains(&val)
1990 /// If a block begins with a statement (possibly a `let` binding) and has an
1991 /// expression, return it.
1992 fn extract_expr_from_first_stmt<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
1993 if block.stmts.is_empty() {
1996 if let StmtKind::Local(ref local) = block.stmts[0].kind {
1997 if let Some(expr) = local.init {
2007 /// If a block begins with an expression (with or without semicolon), return it.
2008 fn extract_first_expr<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
2010 Some(ref expr) if block.stmts.is_empty() => Some(expr),
2011 None if !block.stmts.is_empty() => match block.stmts[0].kind {
2012 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => Some(expr),
2013 StmtKind::Local(..) | StmtKind::Item(..) => None,
2019 /// Returns `true` if expr contains a single break expr without destination label
2021 /// passed expression. The expression may be within a block.
2022 fn is_simple_break_expr(expr: &Expr<'_>) -> bool {
2024 ExprKind::Break(dest, ref passed_expr) if dest.label.is_none() && passed_expr.is_none() => true,
2025 ExprKind::Block(ref b, _) => extract_first_expr(b).map_or(false, |subexpr| is_simple_break_expr(subexpr)),
2030 // To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
2031 // incremented exactly once in the loop body, and initialized to zero
2032 // at the start of the loop.
2033 #[derive(Debug, PartialEq)]
2035 Initial, // Not examined yet
2036 IncrOnce, // Incremented exactly once, may be a loop counter
2037 Declared, // Declared but not (yet) initialized to zero
2042 /// Scan a for loop for variables that are incremented exactly once.
2043 struct IncrementVisitor<'a, 'tcx> {
2044 cx: &'a LateContext<'a, 'tcx>, // context reference
2045 states: FxHashMap<HirId, VarState>, // incremented variables
2046 depth: u32, // depth of conditional expressions
2050 impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
2051 type Map = Map<'tcx>;
2053 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2058 // If node is a variable
2059 if let Some(def_id) = var_def_id(self.cx, expr) {
2060 if let Some(parent) = get_parent_expr(self.cx, expr) {
2061 let state = self.states.entry(def_id).or_insert(VarState::Initial);
2064 ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2065 if lhs.hir_id == expr.hir_id {
2066 if op.node == BinOpKind::Add && is_integer_const(self.cx, rhs, 1) {
2067 *state = match *state {
2068 VarState::Initial if self.depth == 0 => VarState::IncrOnce,
2069 _ => VarState::DontWarn,
2072 // Assigned some other value
2073 *state = VarState::DontWarn;
2077 ExprKind::Assign(ref lhs, _, _) if lhs.hir_id == expr.hir_id => *state = VarState::DontWarn,
2078 ExprKind::AddrOf(BorrowKind::Ref, mutability, _) if mutability == Mutability::Mut => {
2079 *state = VarState::DontWarn
2084 } else if is_loop(expr) || is_conditional(expr) {
2086 walk_expr(self, expr);
2089 } else if let ExprKind::Continue(_) = expr.kind {
2093 walk_expr(self, expr);
2095 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2096 NestedVisitorMap::None
2100 /// Checks whether a variable is initialized to zero at the start of a loop.
2101 struct InitializeVisitor<'a, 'tcx> {
2102 cx: &'a LateContext<'a, 'tcx>, // context reference
2103 end_expr: &'tcx Expr<'tcx>, // the for loop. Stop scanning here.
2107 depth: u32, // depth of conditional expressions
2111 impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
2112 type Map = Map<'tcx>;
2114 fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
2115 // Look for declarations of the variable
2116 if let StmtKind::Local(ref local) = stmt.kind {
2117 if local.pat.hir_id == self.var_id {
2118 if let PatKind::Binding(.., ident, _) = local.pat.kind {
2119 self.name = Some(ident.name);
2121 self.state = if let Some(ref init) = local.init {
2122 if is_integer_const(&self.cx, init, 0) {
2133 walk_stmt(self, stmt);
2136 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2137 if self.state == VarState::DontWarn {
2140 if SpanlessEq::new(self.cx).eq_expr(&expr, self.end_expr) {
2141 self.past_loop = true;
2144 // No need to visit expressions before the variable is
2146 if self.state == VarState::IncrOnce {
2150 // If node is the desired variable, see how it's used
2151 if var_def_id(self.cx, expr) == Some(self.var_id) {
2152 if let Some(parent) = get_parent_expr(self.cx, expr) {
2154 ExprKind::AssignOp(_, ref lhs, _) if lhs.hir_id == expr.hir_id => {
2155 self.state = VarState::DontWarn;
2157 ExprKind::Assign(ref lhs, ref rhs, _) if lhs.hir_id == expr.hir_id => {
2158 self.state = if is_integer_const(&self.cx, rhs, 0) && self.depth == 0 {
2164 ExprKind::AddrOf(BorrowKind::Ref, mutability, _) if mutability == Mutability::Mut => {
2165 self.state = VarState::DontWarn
2172 self.state = VarState::DontWarn;
2175 } else if !self.past_loop && is_loop(expr) {
2176 self.state = VarState::DontWarn;
2178 } else if is_conditional(expr) {
2180 walk_expr(self, expr);
2184 walk_expr(self, expr);
2187 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2188 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
2192 fn var_def_id(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> Option<HirId> {
2193 if let ExprKind::Path(ref qpath) = expr.kind {
2194 let path_res = qpath_res(cx, qpath, expr.hir_id);
2195 if let Res::Local(hir_id) = path_res {
2196 return Some(hir_id);
2202 fn is_loop(expr: &Expr<'_>) -> bool {
2204 ExprKind::Loop(..) => true,
2209 fn is_conditional(expr: &Expr<'_>) -> bool {
2211 ExprKind::Match(..) => true,
2216 fn is_nested(cx: &LateContext<'_, '_>, match_expr: &Expr<'_>, iter_expr: &Expr<'_>) -> bool {
2218 if let Some(loop_block) = get_enclosing_block(cx, match_expr.hir_id);
2219 let parent_node = cx.tcx.hir().get_parent_node(loop_block.hir_id);
2220 if let Some(Node::Expr(loop_expr)) = cx.tcx.hir().find(parent_node);
2222 return is_loop_nested(cx, loop_expr, iter_expr)
2228 fn is_loop_nested(cx: &LateContext<'_, '_>, loop_expr: &Expr<'_>, iter_expr: &Expr<'_>) -> bool {
2229 let mut id = loop_expr.hir_id;
2230 let iter_name = if let Some(name) = path_name(iter_expr) {
2236 let parent = cx.tcx.hir().get_parent_node(id);
2240 match cx.tcx.hir().find(parent) {
2241 Some(Node::Expr(expr)) => {
2242 if let ExprKind::Loop(..) = expr.kind {
2246 Some(Node::Block(block)) => {
2247 let mut block_visitor = LoopNestVisitor {
2249 iterator: iter_name,
2252 walk_block(&mut block_visitor, block);
2253 if block_visitor.nesting == RuledOut {
2257 Some(Node::Stmt(_)) => (),
2266 #[derive(PartialEq, Eq)]
2268 Unknown, // no nesting detected yet
2269 RuledOut, // the iterator is initialized or assigned within scope
2270 LookFurther, // no nesting detected, no further walk required
2273 use self::Nesting::{LookFurther, RuledOut, Unknown};
2275 struct LoopNestVisitor {
2281 impl<'tcx> Visitor<'tcx> for LoopNestVisitor {
2282 type Map = Map<'tcx>;
2284 fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
2285 if stmt.hir_id == self.hir_id {
2286 self.nesting = LookFurther;
2287 } else if self.nesting == Unknown {
2288 walk_stmt(self, stmt);
2292 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2293 if self.nesting != Unknown {
2296 if expr.hir_id == self.hir_id {
2297 self.nesting = LookFurther;
2301 ExprKind::Assign(ref path, _, _) | ExprKind::AssignOp(_, ref path, _) => {
2302 if match_var(path, self.iterator) {
2303 self.nesting = RuledOut;
2306 _ => walk_expr(self, expr),
2310 fn visit_pat(&mut self, pat: &'tcx Pat<'_>) {
2311 if self.nesting != Unknown {
2314 if let PatKind::Binding(.., span_name, _) = pat.kind {
2315 if self.iterator == span_name.name {
2316 self.nesting = RuledOut;
2323 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2324 NestedVisitorMap::None
2328 fn path_name(e: &Expr<'_>) -> Option<Name> {
2329 if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.kind {
2330 let segments = &path.segments;
2331 if segments.len() == 1 {
2332 return Some(segments[0].ident.name);
2338 fn check_infinite_loop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, cond: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) {
2339 if constant(cx, cx.tables, cond).is_some() {
2340 // A pure constant condition (e.g., `while false`) is not linted.
2344 let mut var_visitor = VarCollectorVisitor {
2346 ids: FxHashSet::default(),
2347 def_ids: FxHashMap::default(),
2350 var_visitor.visit_expr(cond);
2351 if var_visitor.skip {
2354 let used_in_condition = &var_visitor.ids;
2355 let no_cond_variable_mutated = if let Some(used_mutably) = mutated_variables(expr, cx) {
2356 used_in_condition.is_disjoint(&used_mutably)
2360 let mutable_static_in_cond = var_visitor.def_ids.iter().any(|(_, v)| *v);
2362 let mut has_break_or_return_visitor = HasBreakOrReturnVisitor {
2363 has_break_or_return: false,
2365 has_break_or_return_visitor.visit_expr(expr);
2366 let has_break_or_return = has_break_or_return_visitor.has_break_or_return;
2368 if no_cond_variable_mutated && !mutable_static_in_cond {
2371 WHILE_IMMUTABLE_CONDITION,
2373 "variables in the condition are not mutated in the loop body",
2375 diag.note("this may lead to an infinite or to a never running loop");
2377 if has_break_or_return {
2378 diag.note("this loop contains `return`s or `break`s");
2379 diag.help("rewrite it as `if cond { loop { } }`");
2386 struct HasBreakOrReturnVisitor {
2387 has_break_or_return: bool,
2390 impl<'a, 'tcx> Visitor<'tcx> for HasBreakOrReturnVisitor {
2391 type Map = Map<'tcx>;
2393 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
2394 if self.has_break_or_return {
2399 ExprKind::Ret(_) | ExprKind::Break(_, _) => {
2400 self.has_break_or_return = true;
2406 walk_expr(self, expr);
2409 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2410 NestedVisitorMap::None
2414 /// Collects the set of variables in an expression
2415 /// Stops analysis if a function call is found
2416 /// Note: In some cases such as `self`, there are no mutable annotation,
2417 /// All variables definition IDs are collected
2418 struct VarCollectorVisitor<'a, 'tcx> {
2419 cx: &'a LateContext<'a, 'tcx>,
2420 ids: FxHashSet<HirId>,
2421 def_ids: FxHashMap<def_id::DefId, bool>,
2425 impl<'a, 'tcx> VarCollectorVisitor<'a, 'tcx> {
2426 fn insert_def_id(&mut self, ex: &'tcx Expr<'_>) {
2428 if let ExprKind::Path(ref qpath) = ex.kind;
2429 if let QPath::Resolved(None, _) = *qpath;
2430 let res = qpath_res(self.cx, qpath, ex.hir_id);
2433 Res::Local(hir_id) => {
2434 self.ids.insert(hir_id);
2436 Res::Def(DefKind::Static, def_id) => {
2437 let mutable = self.cx.tcx.is_mutable_static(def_id);
2438 self.def_ids.insert(def_id, mutable);
2447 impl<'a, 'tcx> Visitor<'tcx> for VarCollectorVisitor<'a, 'tcx> {
2448 type Map = Map<'tcx>;
2450 fn visit_expr(&mut self, ex: &'tcx Expr<'_>) {
2452 ExprKind::Path(_) => self.insert_def_id(ex),
2453 // If there is any function/method call… we just stop analysis
2454 ExprKind::Call(..) | ExprKind::MethodCall(..) => self.skip = true,
2456 _ => walk_expr(self, ex),
2460 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2461 NestedVisitorMap::None
2465 const NEEDLESS_COLLECT_MSG: &str = "avoid using `collect()` when not needed";
2467 fn check_needless_collect<'a, 'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'a, 'tcx>) {
2469 if let ExprKind::MethodCall(ref method, _, ref args) = expr.kind;
2470 if let ExprKind::MethodCall(ref chain_method, _, _) = args[0].kind;
2471 if chain_method.ident.name == sym!(collect) && match_trait_method(cx, &args[0], &paths::ITERATOR);
2472 if let Some(ref generic_args) = chain_method.args;
2473 if let Some(GenericArg::Type(ref ty)) = generic_args.args.get(0);
2475 let ty = cx.tables.node_type(ty.hir_id);
2476 if is_type_diagnostic_item(cx, ty, sym!(vec_type)) ||
2477 is_type_diagnostic_item(cx, ty, sym!(vecdeque_type)) ||
2478 match_type(cx, ty, &paths::BTREEMAP) ||
2479 is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) {
2480 if method.ident.name == sym!(len) {
2481 let span = shorten_needless_collect_span(expr);
2486 NEEDLESS_COLLECT_MSG,
2488 ".count()".to_string(),
2489 Applicability::MachineApplicable,
2492 if method.ident.name == sym!(is_empty) {
2493 let span = shorten_needless_collect_span(expr);
2498 NEEDLESS_COLLECT_MSG,
2500 ".next().is_none()".to_string(),
2501 Applicability::MachineApplicable,
2504 if method.ident.name == sym!(contains) {
2505 let contains_arg = snippet(cx, args[1].span, "??");
2506 let span = shorten_needless_collect_span(expr);
2511 NEEDLESS_COLLECT_MSG,
2513 let (arg, pred) = if contains_arg.starts_with('&') {
2514 ("x", &contains_arg[1..])
2516 ("&x", &*contains_arg)
2518 diag.span_suggestion(
2522 ".any(|{}| x == {})",
2525 Applicability::MachineApplicable,
2535 fn shorten_needless_collect_span(expr: &Expr<'_>) -> Span {
2537 if let ExprKind::MethodCall(_, _, ref args) = expr.kind;
2538 if let ExprKind::MethodCall(_, ref span, _) = args[0].kind;
2540 return expr.span.with_lo(span.lo() - BytePos(1));