Skip to content

Commit 978b1da

Browse files
committed
New lint [filter_map_bool_then]
1 parent 2153c0f commit 978b1da

8 files changed

+171
-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,39 @@
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::{is_from_proc_macro, match_def_path, peel_blocks};
5+
use rustc_errors::Applicability;
6+
use rustc_hir::{Expr, ExprKind};
7+
use rustc_lint::{LateContext, LintContext};
8+
use rustc_middle::lint::in_external_macro;
9+
use rustc_span::Span;
10+
11+
use super::FILTER_MAP_BOOL_THEN;
12+
13+
pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, arg: &Expr<'_>, call_span: Span) {
14+
if !in_external_macro(cx.sess(), expr.span)
15+
&& let ExprKind::Closure(closure) = arg.kind
16+
&& let body = peel_blocks(cx.tcx.hir().body(closure.body).value)
17+
&& let ExprKind::MethodCall(_, recv, [then_arg], _) = body.kind
18+
&& let ExprKind::Closure(then_closure) = then_arg.kind
19+
&& let then_body = peel_blocks(cx.tcx.hir().body(then_closure.body).value)
20+
&& let Some(def_id) = cx.typeck_results().type_dependent_def_id(body.hir_id)
21+
&& match_def_path(cx, def_id, &BOOL_THEN)
22+
&& !is_from_proc_macro(cx, expr)
23+
&& let Some(decl_snippet) = closure.fn_arg_span.and_then(|s| snippet_opt(cx, s))
24+
// NOTE: This will include the `()` (parenthesis) around it. Maybe there's some utils method
25+
// to remove them? `unused_parens` will already take care of this but it may be nice.
26+
&& let Some(filter) = snippet_opt(cx, recv.span)
27+
&& let Some(map) = snippet_opt(cx, then_body.span)
28+
{
29+
span_lint_and_sugg(
30+
cx,
31+
FILTER_MAP_BOOL_THEN,
32+
call_span,
33+
"usage of `bool::then` in `filter_map`",
34+
"use `filter` then `map` instead",
35+
format!("filter({decl_snippet} {filter}).map({decl_snippet} {map})"),
36+
Applicability::MachineApplicable,
37+
);
38+
}
39+
}

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

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

tests/ui/filter_map_bool_then.rs

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

tests/ui/filter_map_bool_then.stderr

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
error: usage of `bool::then` in `filter_map`
2+
--> $DIR/filter_map_bool_then.rs:11:27
3+
|
4+
LL | v.clone().into_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:14:10
11+
|
12+
LL | .filter_map(|i| -> Option<_> { (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:18:10
17+
|
18+
LL | .filter_map(|i| (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:22:10
23+
|
24+
LL | .filter_map(|i| (i.clone() % 2 == 0).then(|| i + 1));
25+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `filter` then `map` instead: `filter(|i| (i.clone() % 2 == 0)).map(|i| i + 1)`
26+
27+
error: aborting due to 4 previous errors
28+

0 commit comments

Comments
 (0)