]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/methods/suspicious_map.rs
Rollup merge of #105109 - rcvalle:rust-kcfi, r=bjorn3
[rust.git] / src / tools / clippy / 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(cx: &LateContext<'_>, expr: &hir::Expr<'_>, count_recv: &hir::Expr<'_>, map_arg: &hir::Expr<'_>) {
12     if_chain! {
13         if is_trait_method(cx, count_recv, sym::Iterator);
14         let closure = expr_or_init(cx, map_arg);
15         if let Some(def_id) = cx.tcx.hir().opt_local_def_id(closure.hir_id);
16         if let Some(body_id) = cx.tcx.hir().maybe_body_owned_by(def_id);
17         let closure_body = cx.tcx.hir().body(body_id);
18         if !cx.typeck_results().expr_ty(closure_body.value).is_unit();
19         then {
20             if let Some(map_mutated_vars) = mutated_variables(closure_body.value, cx) {
21                 // A variable is used mutably inside of the closure. Suppress the lint.
22                 if !map_mutated_vars.is_empty() {
23                     return;
24                 }
25             }
26             span_lint_and_help(
27                 cx,
28                 SUSPICIOUS_MAP,
29                 expr.span,
30                 "this call to `map()` won't have an effect on the call to `count()`",
31                 None,
32                 "make sure you did not confuse `map` with `filter`, `for_each` or `inspect`",
33             );
34         }
35     }
36 }