Skip to content

Commit 0fec99f

Browse files
committed
Auto merge of rust-lang#11115 - Centri3:filter_map_bool_then, r=Jarcho
New lint [`filter_map_bool_then`] Closes rust-lang#9098 changelog: New lint [`filter_map_bool_then`]
2 parents 2153c0f + 3235d9d commit 0fec99f

File tree

8 files changed

+205
-0
lines changed

8 files changed

+205
-0
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -4844,6 +4844,7 @@ Released 2018-09-13
48444844
[`field_reassign_with_default`]: https://rust-lang.github.io/rust-clippy/master/index.html#field_reassign_with_default
48454845
[`filetype_is_file`]: https://rust-lang.github.io/rust-clippy/master/index.html#filetype_is_file
48464846
[`filter_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#filter_map
4847+
[`filter_map_bool_then`]: https://rust-lang.github.io/rust-clippy/master/index.html#filter_map_bool_then
48474848
[`filter_map_identity`]: https://rust-lang.github.io/rust-clippy/master/index.html#filter_map_identity
48484849
[`filter_map_next`]: https://rust-lang.github.io/rust-clippy/master/index.html#filter_map_next
48494850
[`filter_next`]: https://rust-lang.github.io/rust-clippy/master/index.html#filter_next

clippy_lints/src/declared_lints.rs

+1
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
337337
crate::methods::EXPECT_USED_INFO,
338338
crate::methods::EXTEND_WITH_DRAIN_INFO,
339339
crate::methods::FILETYPE_IS_FILE_INFO,
340+
crate::methods::FILTER_MAP_BOOL_THEN_INFO,
340341
crate::methods::FILTER_MAP_IDENTITY_INFO,
341342
crate::methods::FILTER_MAP_NEXT_INFO,
342343
crate::methods::FILTER_NEXT_INFO,
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
use clippy_utils::diagnostics::span_lint_and_sugg;
2+
use clippy_utils::paths::BOOL_THEN;
3+
use clippy_utils::source::snippet_opt;
4+
use clippy_utils::ty::is_copy;
5+
use clippy_utils::{is_from_proc_macro, is_trait_method, match_def_path, peel_blocks};
6+
use rustc_errors::Applicability;
7+
use rustc_hir::{Expr, ExprKind};
8+
use rustc_lint::{LateContext, LintContext};
9+
use rustc_middle::lint::in_external_macro;
10+
use rustc_span::{sym, Span};
11+
12+
use super::FILTER_MAP_BOOL_THEN;
13+
14+
pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, arg: &Expr<'_>, call_span: Span) {
15+
if !in_external_macro(cx.sess(), expr.span)
16+
&& is_trait_method(cx, expr, sym::Iterator)
17+
&& let ExprKind::Closure(closure) = arg.kind
18+
&& let body = cx.tcx.hir().body(closure.body)
19+
&& let value = peel_blocks(body.value)
20+
// Indexing should be fine as `filter_map` always has 1 input, we unfortunately need both
21+
// `inputs` and `params` here as we need both the type and the span
22+
&& let param_ty = closure.fn_decl.inputs[0]
23+
&& let param = body.params[0]
24+
&& is_copy(cx, cx.typeck_results().node_type(param_ty.hir_id).peel_refs())
25+
&& let ExprKind::MethodCall(_, recv, [then_arg], _) = value.kind
26+
&& let ExprKind::Closure(then_closure) = then_arg.kind
27+
&& let then_body = peel_blocks(cx.tcx.hir().body(then_closure.body).value)
28+
&& let Some(def_id) = cx.typeck_results().type_dependent_def_id(value.hir_id)
29+
&& match_def_path(cx, def_id, &BOOL_THEN)
30+
&& !is_from_proc_macro(cx, expr)
31+
&& let Some(param_snippet) = snippet_opt(cx, param.span)
32+
&& let Some(filter) = snippet_opt(cx, recv.span)
33+
&& let Some(map) = snippet_opt(cx, then_body.span)
34+
{
35+
span_lint_and_sugg(
36+
cx,
37+
FILTER_MAP_BOOL_THEN,
38+
call_span,
39+
"usage of `bool::then` in `filter_map`",
40+
"use `filter` then `map` instead",
41+
format!("filter(|&{param_snippet}| {filter}).map(|{param_snippet}| {map})"),
42+
Applicability::MachineApplicable,
43+
);
44+
}
45+
}

clippy_lints/src/methods/mod.rs

+34
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ mod expect_used;
2121
mod extend_with_drain;
2222
mod filetype_is_file;
2323
mod filter_map;
24+
mod filter_map_bool_then;
2425
mod filter_map_identity;
2526
mod filter_map_next;
2627
mod filter_next;
@@ -3475,6 +3476,37 @@ declare_clippy_lint! {
34753476
"disallows `.skip(0)`"
34763477
}
34773478

3479+
declare_clippy_lint! {
3480+
/// ### What it does
3481+
/// Checks for usage of `bool::then` in `Iterator::filter_map`.
3482+
///
3483+
/// ### Why is this bad?
3484+
/// This can be written with `filter` then `map` instead, which would reduce nesting and
3485+
/// separates the filtering from the transformation phase. This comes with no cost to
3486+
/// performance and is just cleaner.
3487+
///
3488+
/// ### Limitations
3489+
/// Does not lint `bool::then_some`, as it eagerly evaluates its arguments rather than lazily.
3490+
/// This can create differing behavior, so better safe than sorry.
3491+
///
3492+
/// ### Example
3493+
/// ```rust
3494+
/// # fn really_expensive_fn(i: i32) -> i32 { i }
3495+
/// # let v = vec![];
3496+
/// _ = v.into_iter().filter_map(|i| (i % 2 == 0).then(|| really_expensive_fn(i)));
3497+
/// ```
3498+
/// Use instead:
3499+
/// ```rust
3500+
/// # fn really_expensive_fn(i: i32) -> i32 { i }
3501+
/// # let v = vec![];
3502+
/// _ = v.into_iter().filter(|i| i % 2 == 0).map(|i| really_expensive_fn(i));
3503+
/// ```
3504+
#[clippy::version = "1.72.0"]
3505+
pub FILTER_MAP_BOOL_THEN,
3506+
style,
3507+
"checks for usage of `bool::then` in `Iterator::filter_map`"
3508+
}
3509+
34783510
pub struct Methods {
34793511
avoid_breaking_exported_api: bool,
34803512
msrv: Msrv,
@@ -3612,6 +3644,7 @@ impl_lint_pass!(Methods => [
36123644
FORMAT_COLLECT,
36133645
STRING_LIT_CHARS_ANY,
36143646
ITER_SKIP_ZERO,
3647+
FILTER_MAP_BOOL_THEN,
36153648
]);
36163649

36173650
/// Extracts a method call name, args, and `Span` of the method name.
@@ -3889,6 +3922,7 @@ impl Methods {
38893922
},
38903923
("filter_map", [arg]) => {
38913924
unnecessary_filter_map::check(cx, expr, arg, name);
3925+
filter_map_bool_then::check(cx, expr, arg, call_span);
38923926
filter_map_identity::check(cx, expr, arg, span);
38933927
},
38943928
("find_map", [arg]) => {

clippy_utils/src/paths.rs

+2
Original file line numberDiff line numberDiff line change
@@ -163,3 +163,5 @@ pub const OPTION_EXPECT: [&str; 4] = ["core", "option", "Option", "expect"];
163163
pub const FORMATTER: [&str; 3] = ["core", "fmt", "Formatter"];
164164
pub const DEBUG_STRUCT: [&str; 4] = ["core", "fmt", "builders", "DebugStruct"];
165165
pub const ORD_CMP: [&str; 4] = ["core", "cmp", "Ord", "cmp"];
166+
#[expect(clippy::invalid_paths)] // not sure why it thinks this, it works so
167+
pub const BOOL_THEN: [&str; 4] = ["core", "bool", "<impl bool>", "then"];

tests/ui/filter_map_bool_then.fixed

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
//@run-rustfix
2+
//@aux-build:proc_macros.rs:proc-macro
3+
#![allow(
4+
clippy::clone_on_copy,
5+
clippy::map_identity,
6+
clippy::unnecessary_lazy_evaluations,
7+
unused
8+
)]
9+
#![warn(clippy::filter_map_bool_then)]
10+
11+
#[macro_use]
12+
extern crate proc_macros;
13+
14+
#[derive(Clone, PartialEq)]
15+
struct NonCopy;
16+
17+
fn main() {
18+
let v = vec![1, 2, 3, 4, 5, 6];
19+
v.clone().iter().filter(|&i| (i % 2 == 0)).map(|i| i + 1);
20+
v.clone().into_iter().filter(|&i| (i % 2 == 0)).map(|i| i + 1);
21+
v.clone()
22+
.into_iter()
23+
.filter(|&i| (i % 2 == 0)).map(|i| i + 1);
24+
v.clone()
25+
.into_iter()
26+
.filter(|&i| i != 1000)
27+
.filter(|&i| (i % 2 == 0)).map(|i| i + 1);
28+
v.iter()
29+
.copied()
30+
.filter(|&i| i != 1000)
31+
.filter(|&i| (i.clone() % 2 == 0)).map(|i| i + 1);
32+
// Do not lint
33+
let v = vec![NonCopy, NonCopy];
34+
v.clone().iter().filter_map(|i| (i == &NonCopy).then(|| i));
35+
external! {
36+
let v = vec![1, 2, 3, 4, 5, 6];
37+
v.clone().into_iter().filter_map(|i| (i % 2 == 0).then(|| i + 1));
38+
}
39+
with_span! {
40+
span
41+
let v = vec![1, 2, 3, 4, 5, 6];
42+
v.clone().into_iter().filter_map(|i| (i % 2 == 0).then(|| i + 1));
43+
}
44+
}

tests/ui/filter_map_bool_then.rs

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
//@run-rustfix
2+
//@aux-build:proc_macros.rs:proc-macro
3+
#![allow(
4+
clippy::clone_on_copy,
5+
clippy::map_identity,
6+
clippy::unnecessary_lazy_evaluations,
7+
unused
8+
)]
9+
#![warn(clippy::filter_map_bool_then)]
10+
11+
#[macro_use]
12+
extern crate proc_macros;
13+
14+
#[derive(Clone, PartialEq)]
15+
struct NonCopy;
16+
17+
fn main() {
18+
let v = vec![1, 2, 3, 4, 5, 6];
19+
v.clone().iter().filter_map(|i| (i % 2 == 0).then(|| i + 1));
20+
v.clone().into_iter().filter_map(|i| (i % 2 == 0).then(|| i + 1));
21+
v.clone()
22+
.into_iter()
23+
.filter_map(|i| -> Option<_> { (i % 2 == 0).then(|| i + 1) });
24+
v.clone()
25+
.into_iter()
26+
.filter(|&i| i != 1000)
27+
.filter_map(|i| (i % 2 == 0).then(|| i + 1));
28+
v.iter()
29+
.copied()
30+
.filter(|&i| i != 1000)
31+
.filter_map(|i| (i.clone() % 2 == 0).then(|| i + 1));
32+
// Do not lint
33+
let v = vec![NonCopy, NonCopy];
34+
v.clone().iter().filter_map(|i| (i == &NonCopy).then(|| i));
35+
external! {
36+
let v = vec![1, 2, 3, 4, 5, 6];
37+
v.clone().into_iter().filter_map(|i| (i % 2 == 0).then(|| i + 1));
38+
}
39+
with_span! {
40+
span
41+
let v = vec![1, 2, 3, 4, 5, 6];
42+
v.clone().into_iter().filter_map(|i| (i % 2 == 0).then(|| i + 1));
43+
}
44+
}

tests/ui/filter_map_bool_then.stderr

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
error: usage of `bool::then` in `filter_map`
2+
--> $DIR/filter_map_bool_then.rs:19:22
3+
|
4+
LL | v.clone().iter().filter_map(|i| (i % 2 == 0).then(|| i + 1));
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `filter` then `map` instead: `filter(|&i| (i % 2 == 0)).map(|i| i + 1)`
6+
|
7+
= note: `-D clippy::filter-map-bool-then` implied by `-D warnings`
8+
9+
error: usage of `bool::then` in `filter_map`
10+
--> $DIR/filter_map_bool_then.rs:20:27
11+
|
12+
LL | v.clone().into_iter().filter_map(|i| (i % 2 == 0).then(|| i + 1));
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `filter` then `map` instead: `filter(|&i| (i % 2 == 0)).map(|i| i + 1)`
14+
15+
error: usage of `bool::then` in `filter_map`
16+
--> $DIR/filter_map_bool_then.rs:23:10
17+
|
18+
LL | .filter_map(|i| -> Option<_> { (i % 2 == 0).then(|| i + 1) });
19+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `filter` then `map` instead: `filter(|&i| (i % 2 == 0)).map(|i| i + 1)`
20+
21+
error: usage of `bool::then` in `filter_map`
22+
--> $DIR/filter_map_bool_then.rs:27:10
23+
|
24+
LL | .filter_map(|i| (i % 2 == 0).then(|| i + 1));
25+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `filter` then `map` instead: `filter(|&i| (i % 2 == 0)).map(|i| i + 1)`
26+
27+
error: usage of `bool::then` in `filter_map`
28+
--> $DIR/filter_map_bool_then.rs:31:10
29+
|
30+
LL | .filter_map(|i| (i.clone() % 2 == 0).then(|| i + 1));
31+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `filter` then `map` instead: `filter(|&i| (i.clone() % 2 == 0)).map(|i| i + 1)`
32+
33+
error: aborting due to 5 previous errors
34+

0 commit comments

Comments
 (0)