Skip to content

Commit 23eb869

Browse files
mathstufcamsteffen
authored andcommitted
Fix suspicious_map false positives
1 parent 52c25e9 commit 23eb869

File tree

5 files changed

+126
-16
lines changed

5 files changed

+126
-16
lines changed

clippy_lints/src/methods/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1739,7 +1739,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods {
17391739
unnecessary_filter_map::check(cx, expr, arg_lists[0]);
17401740
filter_map_identity::check(cx, expr, arg_lists[0], method_spans[0]);
17411741
},
1742-
["count", "map"] => suspicious_map::check(cx, expr),
1742+
["count", "map"] => suspicious_map::check(cx, expr, arg_lists[1], arg_lists[0]),
17431743
["assume_init"] => uninit_assumed_init::check(cx, &arg_lists[0][0], expr),
17441744
["unwrap_or", arith @ ("checked_add" | "checked_sub" | "checked_mul")] => {
17451745
manual_saturating_arithmetic::check(cx, expr, &arg_lists, &arith["checked_".len()..])
+30-10
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,36 @@
1-
use crate::utils::span_lint_and_help;
1+
use crate::utils::{span_lint_and_help, expr_or_init, is_trait_method};
22
use rustc_hir as hir;
33
use rustc_lint::LateContext;
4+
use if_chain::if_chain;
5+
use crate::utils::usage::mutated_variables;
6+
use rustc_span::sym;
47

58
use super::SUSPICIOUS_MAP;
69

7-
pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
8-
span_lint_and_help(
9-
cx,
10-
SUSPICIOUS_MAP,
11-
expr.span,
12-
"this call to `map()` won't have an effect on the call to `count()`",
13-
None,
14-
"make sure you did not confuse `map` with `filter` or `for_each`",
15-
);
10+
pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, map_args: &[hir::Expr<'_>], count_args: &[hir::Expr<'_>]) {
11+
if_chain! {
12+
if let [count_recv] = count_args;
13+
if let [_, map_arg] = map_args;
14+
if is_trait_method(cx, count_recv, sym::Iterator);
15+
let closure = expr_or_init(cx, map_arg);
16+
if let Some(body_id) = cx.tcx.hir().maybe_body_owned_by(closure.hir_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` or `for_each`",
33+
);
34+
}
35+
}
1636
}

clippy_utils/src/lib.rs

+59-4
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,9 @@ use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
6262
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
6363
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
6464
use rustc_hir::{
65-
def, Arm, Block, Body, Constness, CrateItem, Expr, ExprKind, FnDecl, ForeignItem, GenericArgs, GenericParam, HirId,
66-
Impl, ImplItem, ImplItemKind, Item, ItemKind, LangItem, Lifetime, Local, MacroDef, MatchSource, Node, Param, Pat,
67-
PatKind, Path, PathSegment, QPath, Stmt, StructField, TraitItem, TraitItemKind, TraitRef, TyKind, Unsafety,
68-
Variant, Visibility,
65+
def, Arm, BindingAnnotation, Block, Body, Constness, CrateItem, Expr, ExprKind, FnDecl, ForeignItem, GenericArgs, GenericParam,HirId, Impl,
66+
ImplItem, ImplItemKind, Item, ItemKind, LangItem, Lifetime, Local, MacroDef, MatchSource, Node,Param, Pat, PatKind, Path, PathSegment, QPath,
67+
Stmt, StructField, TraitItem, TraitItemKind, TraitRef, TyKind, Unsafety,Variant, Visibility,
6968
};
7069
use rustc_infer::infer::TyCtxtInferExt;
7170
use rustc_lint::{LateContext, Level, Lint, LintContext};
@@ -138,6 +137,62 @@ pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
138137
rhs.ctxt() != lhs.ctxt()
139138
}
140139

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<'a, 'b, 'tcx: 'b>(cx: &LateContext<'tcx>, mut expr: &'a Expr<'b>) -> &'a Expr<'b> {
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+
141196
/// Returns `true` if the given `NodeId` is inside a constant context
142197
///
143198
/// # 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)