Skip to content

Commit 0e042d2

Browse files
committed
Auto merge of #6831 - camsteffen:suspicious-map, r=Y-Nak,flip1995
Fix suspicious_map false positives changelog: Fix suspicious_map false positives Fixes #5253 Replaces #5375
2 parents 52c25e9 + 59dba04 commit 0e042d2

File tree

5 files changed

+128
-16
lines changed

5 files changed

+128
-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()..])
+35-10
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,41 @@
1-
use crate::utils::span_lint_and_help;
1+
use crate::utils::usage::mutated_variables;
2+
use crate::utils::{expr_or_init, is_trait_method, span_lint_and_help};
3+
use if_chain::if_chain;
24
use rustc_hir as hir;
35
use rustc_lint::LateContext;
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>(
11+
cx: &LateContext<'tcx>,
12+
expr: &hir::Expr<'_>,
13+
map_args: &[hir::Expr<'_>],
14+
count_args: &[hir::Expr<'_>],
15+
) {
16+
if_chain! {
17+
if let [count_recv] = count_args;
18+
if let [_, map_arg] = map_args;
19+
if is_trait_method(cx, count_recv, sym::Iterator);
20+
let closure = expr_or_init(cx, map_arg);
21+
if let Some(body_id) = cx.tcx.hir().maybe_body_owned_by(closure.hir_id);
22+
let closure_body = cx.tcx.hir().body(body_id);
23+
if !cx.typeck_results().expr_ty(&closure_body.value).is_unit();
24+
then {
25+
if let Some(map_mutated_vars) = mutated_variables(&closure_body.value, cx) {
26+
// A variable is used mutably inside of the closure. Suppress the lint.
27+
if !map_mutated_vars.is_empty() {
28+
return;
29+
}
30+
}
31+
span_lint_and_help(
32+
cx,
33+
SUSPICIOUS_MAP,
34+
expr.span,
35+
"this call to `map()` won't have an effect on the call to `count()`",
36+
None,
37+
"make sure you did not confuse `map` with `filter` or `for_each`",
38+
);
39+
}
40+
}
1641
}

clippy_utils/src/lib.rs

+56-4
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,10 @@ 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,
66+
GenericParam, HirId, Impl, ImplItem, ImplItemKind, Item, ItemKind, LangItem, Lifetime, Local, MacroDef,
67+
MatchSource, Node, Param, Pat, PatKind, Path, PathSegment, QPath, Stmt, StructField, TraitItem, TraitItemKind,
68+
TraitRef, TyKind, Unsafety, Variant, Visibility,
6969
};
7070
use rustc_infer::infer::TyCtxtInferExt;
7171
use rustc_lint::{LateContext, Level, Lint, LintContext};
@@ -138,6 +138,58 @@ pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
138138
rhs.ctxt() != lhs.ctxt()
139139
}
140140

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