]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/suspicious_map.rs
Auto merge of #6957 - camsteffen:eq-ty-kind, r=flip1995
[rust.git] / clippy_lints / src / methods / suspicious_map.rs
1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::usage::mutated_variables;
3 use clippy_utils::{expr_or_init, is_trait_method};
4 use if_chain::if_chain;
5 use rustc_hir as hir;
6 use rustc_lint::LateContext;
7 use rustc_span::sym;
8
9 use super::SUSPICIOUS_MAP;
10
11 pub fn check<'tcx>(
12     cx: &LateContext<'tcx>,
13     expr: &hir::Expr<'_>,
14     map_args: &[hir::Expr<'_>],
15     count_args: &[hir::Expr<'_>],
16 ) {
17     if_chain! {
18         if let [count_recv] = count_args;
19         if let [_, map_arg] = map_args;
20         if is_trait_method(cx, count_recv, sym::Iterator);
21         let closure = expr_or_init(cx, map_arg);
22         if let Some(body_id) = cx.tcx.hir().maybe_body_owned_by(closure.hir_id);
23         let closure_body = cx.tcx.hir().body(body_id);
24         if !cx.typeck_results().expr_ty(&closure_body.value).is_unit();
25         then {
26             if let Some(map_mutated_vars) = mutated_variables(&closure_body.value, cx) {
27                 // A variable is used mutably inside of the closure. Suppress the lint.
28                 if !map_mutated_vars.is_empty() {
29                     return;
30                 }
31             }
32             span_lint_and_help(
33                 cx,
34                 SUSPICIOUS_MAP,
35                 expr.span,
36                 "this call to `map()` won't have an effect on the call to `count()`",
37                 None,
38                 "make sure you did not confuse `map` with `filter` or `for_each`",
39             );
40         }
41     }
42 }