Skip to content

Commit b5c31ad

Browse files
mathstufcamsteffen
authored andcommitted
Fix suspicious_map false positives
1 parent d02ca3b commit b5c31ad

File tree

4 files changed

+125
-20
lines changed

4 files changed

+125
-20
lines changed

clippy_lints/src/methods/mod.rs

+30-16
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,12 @@ use crate::consts::{constant, Constant};
3333
use crate::utils::eager_or_lazy::is_lazyness_candidate;
3434
use crate::utils::usage::mutated_variables;
3535
use crate::utils::{
36-
contains_return, contains_ty, get_parent_expr, get_trait_def_id, has_iter_method, higher, implements_trait,
37-
in_macro, is_copy, is_expn_of, is_type_diagnostic_item, iter_input_pats, last_path_segment, match_def_path,
38-
match_qpath, match_trait_method, match_type, meets_msrv, method_calls, method_chain_args, path_to_local_id, paths,
39-
remove_blocks, return_ty, single_segment_path, snippet, snippet_with_applicability, snippet_with_macro_callsite,
40-
span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, strip_pat_refs, sugg, walk_ptrs_ty_depth,
41-
SpanlessEq,
36+
contains_return, contains_ty, expr_or_init, get_parent_expr, get_trait_def_id, has_iter_method, higher,
37+
implements_trait, in_macro, is_copy, is_expn_of, is_type_diagnostic_item, iter_input_pats, last_path_segment,
38+
match_def_path, match_qpath, match_trait_method, match_type, meets_msrv, method_calls, method_chain_args,
39+
path_to_local_id, paths, remove_blocks, return_ty, single_segment_path, snippet, snippet_with_applicability,
40+
snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, strip_pat_refs,
41+
sugg, walk_ptrs_ty_depth, SpanlessEq,
4242
};
4343

4444
declare_clippy_lint! {
@@ -1709,7 +1709,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods {
17091709
unnecessary_filter_map::lint(cx, expr, arg_lists[0]);
17101710
filter_map_identity::check(cx, expr, arg_lists[0], method_spans[0]);
17111711
},
1712-
["count", "map"] => lint_suspicious_map(cx, expr),
1712+
["count", "map"] => lint_suspicious_map(cx, expr, &arg_lists[1][1]),
17131713
["assume_init"] => lint_maybe_uninit(cx, &arg_lists[0][0], expr),
17141714
["unwrap_or", arith @ ("checked_add" | "checked_sub" | "checked_mul")] => {
17151715
manual_saturating_arithmetic::lint(cx, expr, &arg_lists, &arith["checked_".len()..])
@@ -3758,15 +3758,29 @@ fn is_maybe_uninit_ty_valid(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
37583758
}
37593759
}
37603760

3761-
fn lint_suspicious_map(cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
3762-
span_lint_and_help(
3763-
cx,
3764-
SUSPICIOUS_MAP,
3765-
expr.span,
3766-
"this call to `map()` won't have an effect on the call to `count()`",
3767-
None,
3768-
"make sure you did not confuse `map` with `filter` or `for_each`",
3769-
);
3761+
fn lint_suspicious_map<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, map_arg: &'tcx hir::Expr<'tcx>) {
3762+
let closure = expr_or_init(cx, map_arg);
3763+
if_chain! {
3764+
if let Some(body_id) = cx.tcx.hir().maybe_body_owned_by(closure.hir_id);
3765+
let closure_body = cx.tcx.hir().body(body_id);
3766+
if !cx.typeck_results().expr_ty(&closure_body.value).is_unit();
3767+
then {
3768+
if let Some(map_mutated_vars) = mutated_variables(&closure_body.value, cx) {
3769+
// A variable is used mutably inside of the closure. Suppress the lint.
3770+
if !map_mutated_vars.is_empty() {
3771+
return;
3772+
}
3773+
}
3774+
span_lint_and_help(
3775+
cx,
3776+
SUSPICIOUS_MAP,
3777+
expr.span,
3778+
"this call to `map()` won't have an effect on the call to `count()`",
3779+
None,
3780+
"make sure you did not confuse `map` with `filter` or `for_each`",
3781+
);
3782+
}
3783+
}
37703784
}
37713785

37723786
const OPTION_AS_REF_DEREF_MSRV: RustcVersion = RustcVersion::new(1, 40, 0);

clippy_utils/src/lib.rs

+59-3
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,9 @@ use rustc_hir::def_id::{DefId, LOCAL_CRATE};
6363
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
6464
use rustc_hir::Node;
6565
use rustc_hir::{
66-
def, Arm, Block, Body, Constness, Crate, Expr, ExprKind, FnDecl, GenericArgs, HirId, Impl, ImplItem, ImplItemKind,
67-
Item, ItemKind, LangItem, MatchSource, Param, Pat, PatKind, Path, PathSegment, QPath, TraitItem, TraitItemKind,
68-
TraitRef, TyKind, Unsafety,
66+
def, Arm, BindingAnnotation, Block, Body, Constness, Crate, Expr, ExprKind, FnDecl, GenericArgs, HirId, Impl,
67+
ImplItem, ImplItemKind, Item, ItemKind, LangItem, MatchSource, Param, Pat, PatKind, Path, PathSegment, QPath,
68+
TraitItem, TraitItemKind, TraitRef, TyKind, Unsafety,
6969
};
7070
use rustc_infer::infer::TyCtxtInferExt;
7171
use rustc_lint::{LateContext, Level, Lint, LintContext};
@@ -137,6 +137,62 @@ pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
137137
rhs.ctxt() != lhs.ctxt()
138138
}
139139

140+
/// If the given expression is a local binding, find the initializer expression.
141+
/// If that initializer expression is another local binding, find its initializer again.
142+
/// This process repeats as long as possible (but usually no more than once). Initializer
143+
/// expressions with adjustments are ignored. If this is not desired, use [`find_binding_init`]
144+
/// instead.
145+
///
146+
/// Examples:
147+
/// ```ignore
148+
/// let abc = 1;
149+
/// // ^ output
150+
/// let def = abc;
151+
/// dbg!(def)
152+
/// // ^^^ input
153+
///
154+
/// // or...
155+
/// let abc = 1;
156+
/// let def = abc + 2;
157+
/// // ^^^^^^^ output
158+
/// dbg!(def)
159+
/// // ^^^ input
160+
/// ```
161+
pub fn expr_or_init<'tcx>(cx: &LateContext<'tcx>, mut expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
162+
while let Some(init) = path_to_local(expr)
163+
.and_then(|id| find_binding_init(cx, id))
164+
.filter(|init| cx.typeck_results().expr_adjustments(init).is_empty())
165+
{
166+
expr = init;
167+
}
168+
expr
169+
}
170+
171+
/// Finds the initializer expression for a local binding. Returns `None` if the binding is mutable.
172+
/// By only considering immutable bindings, we guarantee that the returned expression represents the
173+
/// value of the binding wherever it is referenced.
174+
///
175+
/// Example:
176+
/// ```ignore
177+
/// let abc = 1;
178+
/// // ^ output
179+
/// dbg!(abc)
180+
/// // ^^^ input
181+
/// ```
182+
pub fn find_binding_init<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Expr<'tcx>> {
183+
let hir = cx.tcx.hir();
184+
if_chain! {
185+
if let Some(Node::Binding(pat)) = hir.find(hir_id);
186+
if matches!(pat.kind, PatKind::Binding(BindingAnnotation::Unannotated, ..));
187+
let parent = hir.get_parent_node(hir_id);
188+
if let Some(Node::Local(local)) = hir.find(parent);
189+
then {
190+
return local.init;
191+
}
192+
}
193+
None
194+
}
195+
140196
/// Returns `true` if the given `NodeId` is inside a constant context
141197
///
142198
/// # Example

tests/ui/suspicious_map.rs

+27
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,31 @@
22

33
fn main() {
44
let _ = (0..3).map(|x| x + 2).count();
5+
6+
let f = |x| x + 1;
7+
let _ = (0..3).map(f).count();
8+
}
9+
10+
fn negative() {
11+
// closure with side effects
12+
let mut sum = 0;
13+
let _ = (0..3).map(|x| sum += x).count();
14+
15+
// closure variable with side effects
16+
let ext_closure = |x| sum += x;
17+
let _ = (0..3).map(ext_closure).count();
18+
19+
// closure that returns unit
20+
let _ = (0..3)
21+
.map(|x| {
22+
// do nothing
23+
})
24+
.count();
25+
26+
// external function
27+
let _ = (0..3).map(do_something).count();
28+
}
29+
30+
fn do_something<T>(t: T) -> String {
31+
unimplemented!()
532
}

tests/ui/suspicious_map.stderr

+9-1
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,13 @@ LL | let _ = (0..3).map(|x| x + 2).count();
77
= note: `-D clippy::suspicious-map` implied by `-D warnings`
88
= help: make sure you did not confuse `map` with `filter` or `for_each`
99

10-
error: aborting due to previous error
10+
error: this call to `map()` won't have an effect on the call to `count()`
11+
--> $DIR/suspicious_map.rs:7:13
12+
|
13+
LL | let _ = (0..3).map(f).count();
14+
| ^^^^^^^^^^^^^^^^^^^^^
15+
|
16+
= help: make sure you did not confuse `map` with `filter` or `for_each`
17+
18+
error: aborting due to 2 previous errors
1119

0 commit comments

Comments
 (0)