2021-03-25 18:29:11 +00:00
|
|
|
use clippy_utils::diagnostics::span_lint_and_help;
|
|
|
|
use clippy_utils::usage::mutated_variables;
|
|
|
|
use clippy_utils::{expr_or_init, is_trait_method};
|
|
|
|
use if_chain::if_chain;
|
2021-03-12 14:30:50 +00:00
|
|
|
use rustc_hir as hir;
|
|
|
|
use rustc_lint::LateContext;
|
2021-03-25 18:29:11 +00:00
|
|
|
use rustc_span::sym;
|
2021-03-12 14:30:50 +00:00
|
|
|
|
|
|
|
use super::SUSPICIOUS_MAP;
|
|
|
|
|
2021-04-08 15:50:13 +00:00
|
|
|
pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, count_recv: &hir::Expr<'_>, map_arg: &hir::Expr<'_>) {
|
2021-03-25 18:29:11 +00:00
|
|
|
if_chain! {
|
|
|
|
if is_trait_method(cx, count_recv, sym::Iterator);
|
|
|
|
let closure = expr_or_init(cx, map_arg);
|
2022-07-20 02:51:52 +00:00
|
|
|
if let Some(def_id) = cx.tcx.hir().opt_local_def_id(closure.hir_id);
|
|
|
|
if let Some(body_id) = cx.tcx.hir().maybe_body_owned_by(def_id);
|
2021-03-25 18:29:11 +00:00
|
|
|
let closure_body = cx.tcx.hir().body(body_id);
|
2022-09-09 11:36:26 +00:00
|
|
|
if !cx.typeck_results().expr_ty(closure_body.value).is_unit();
|
2021-03-25 18:29:11 +00:00
|
|
|
then {
|
2022-09-09 11:36:26 +00:00
|
|
|
if let Some(map_mutated_vars) = mutated_variables(closure_body.value, cx) {
|
2021-03-25 18:29:11 +00:00
|
|
|
// A variable is used mutably inside of the closure. Suppress the lint.
|
|
|
|
if !map_mutated_vars.is_empty() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
span_lint_and_help(
|
|
|
|
cx,
|
|
|
|
SUSPICIOUS_MAP,
|
|
|
|
expr.span,
|
|
|
|
"this call to `map()` won't have an effect on the call to `count()`",
|
|
|
|
None,
|
2021-10-07 09:21:30 +00:00
|
|
|
"make sure you did not confuse `map` with `filter`, `for_each` or `inspect`",
|
2021-03-25 18:29:11 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
2021-03-12 14:30:50 +00:00
|
|
|
}
|