Skip to content

Commit d469ee5

Browse files
committed
Split filter_map into manual_filter_map
1 parent 48aac25 commit d469ee5

File tree

7 files changed

+198
-23
lines changed

7 files changed

+198
-23
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2034,6 +2034,7 @@ Released 2018-09-13
20342034
[`macro_use_imports`]: https://rust-lang.github.io/rust-clippy/master/index.html#macro_use_imports
20352035
[`main_recursion`]: https://rust-lang.github.io/rust-clippy/master/index.html#main_recursion
20362036
[`manual_async_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_async_fn
2037+
[`manual_filter_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_filter_map
20372038
[`manual_memcpy`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_memcpy
20382039
[`manual_non_exhaustive`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_non_exhaustive
20392040
[`manual_ok_or`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_ok_or

clippy_lints/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -743,6 +743,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
743743
&methods::ITER_NTH,
744744
&methods::ITER_NTH_ZERO,
745745
&methods::ITER_SKIP_NEXT,
746+
&methods::MANUAL_FILTER_MAP,
746747
&methods::MANUAL_SATURATING_ARITHMETIC,
747748
&methods::MAP_COLLECT_RESULT_UNIT,
748749
&methods::MAP_FLATTEN,
@@ -1521,6 +1522,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
15211522
LintId::of(&methods::ITER_NTH),
15221523
LintId::of(&methods::ITER_NTH_ZERO),
15231524
LintId::of(&methods::ITER_SKIP_NEXT),
1525+
LintId::of(&methods::MANUAL_FILTER_MAP),
15241526
LintId::of(&methods::MANUAL_SATURATING_ARITHMETIC),
15251527
LintId::of(&methods::MAP_COLLECT_RESULT_UNIT),
15261528
LintId::of(&methods::NEW_RET_NO_SELF),
@@ -1815,6 +1817,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
18151817
LintId::of(&methods::CLONE_ON_COPY),
18161818
LintId::of(&methods::FILTER_NEXT),
18171819
LintId::of(&methods::FLAT_MAP_IDENTITY),
1820+
LintId::of(&methods::MANUAL_FILTER_MAP),
18181821
LintId::of(&methods::OPTION_AS_REF_DEREF),
18191822
LintId::of(&methods::SEARCH_IS_SOME),
18201823
LintId::of(&methods::SKIP_WHILE_NEXT),

clippy_lints/src/methods/mod.rs

Lines changed: 96 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ use if_chain::if_chain;
1414
use rustc_ast::ast;
1515
use rustc_errors::Applicability;
1616
use rustc_hir as hir;
17-
use rustc_hir::{TraitItem, TraitItemKind};
17+
use rustc_hir::def::Res;
18+
use rustc_hir::{Expr, ExprKind, PatKind, QPath, TraitItem, TraitItemKind, UnOp};
1819
use rustc_lint::{LateContext, LateLintPass, Lint, LintContext};
1920
use rustc_middle::lint::in_external_macro;
2021
use rustc_middle::ty::{self, TraitRef, Ty, TyS};
@@ -449,6 +450,32 @@ declare_clippy_lint! {
449450
"using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
450451
}
451452

453+
declare_clippy_lint! {
454+
/// **What it does:** Checks for usage of `_.filter(_).map(_)` that can be written more simply
455+
/// as `filter_map(_)`.
456+
///
457+
/// **Why is this bad?** Redundant code in the `filter` and `map` operations is poor style and
458+
/// less performant.
459+
///
460+
/// **Known problems:** None.
461+
///
462+
/// **Example:**
463+
/// Bad:
464+
/// ```rust
465+
/// (0_i32..10)
466+
/// .filter(|n| n.checked_add(1).is_some())
467+
/// .map(|n| n.checked_add(1).unwrap());
468+
/// ```
469+
///
470+
/// Good:
471+
/// ```rust
472+
/// (0_i32..10).filter_map(|n| n.checked_add(1));
473+
/// ```
474+
pub MANUAL_FILTER_MAP,
475+
complexity,
476+
"using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
477+
}
478+
452479
declare_clippy_lint! {
453480
/// **What it does:** Checks for usage of `_.filter_map(_).next()`.
454481
///
@@ -1442,6 +1469,7 @@ impl_lint_pass!(Methods => [
14421469
FILTER_NEXT,
14431470
SKIP_WHILE_NEXT,
14441471
FILTER_MAP,
1472+
MANUAL_FILTER_MAP,
14451473
FILTER_MAP_NEXT,
14461474
FLAT_MAP_IDENTITY,
14471475
FIND_MAP,
@@ -1508,7 +1536,7 @@ impl<'tcx> LateLintPass<'tcx> for Methods {
15081536
["next", "filter"] => lint_filter_next(cx, expr, arg_lists[1]),
15091537
["next", "skip_while"] => lint_skip_while_next(cx, expr, arg_lists[1]),
15101538
["next", "iter"] => lint_iter_next(cx, expr, arg_lists[1]),
1511-
["map", "filter"] => lint_filter_map(cx, expr, arg_lists[1], arg_lists[0]),
1539+
["map", "filter"] => lint_filter_map(cx, expr),
15121540
["map", "filter_map"] => lint_filter_map_map(cx, expr, arg_lists[1], arg_lists[0]),
15131541
["next", "filter_map"] => lint_filter_map_next(cx, expr, arg_lists[1], self.msrv.as_ref()),
15141542
["map", "find"] => lint_find_map(cx, expr, arg_lists[1], arg_lists[0]),
@@ -2956,17 +2984,72 @@ fn lint_skip_while_next<'tcx>(
29562984
}
29572985

29582986
/// lint use of `filter().map()` for `Iterators`
2959-
fn lint_filter_map<'tcx>(
2960-
cx: &LateContext<'tcx>,
2961-
expr: &'tcx hir::Expr<'_>,
2962-
_filter_args: &'tcx [hir::Expr<'_>],
2963-
_map_args: &'tcx [hir::Expr<'_>],
2964-
) {
2965-
// lint if caller of `.filter().map()` is an Iterator
2966-
if match_trait_method(cx, expr, &paths::ITERATOR) {
2967-
let msg = "called `filter(..).map(..)` on an `Iterator`";
2968-
let hint = "this is more succinctly expressed by calling `.filter_map(..)` instead";
2969-
span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2987+
fn lint_filter_map<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
2988+
if_chain! {
2989+
if let ExprKind::MethodCall(_, _, [map_recv, map_arg], map_span) = expr.kind;
2990+
if let ExprKind::MethodCall(_, _, [_, filter_arg], filter_span) = map_recv.kind;
2991+
if match_trait_method(cx, expr, &paths::ITERATOR);
2992+
2993+
// filter(|x| ...is_some())...
2994+
if let ExprKind::Closure(_, _, filter_body_id, ..) = filter_arg.kind;
2995+
let filter_body = cx.tcx.hir().body(filter_body_id);
2996+
if let [filter_param] = filter_body.params;
2997+
// optional ref pattern: `filter(|&x| ..)`
2998+
let (filter_pat, is_filter_param_ref) = if let PatKind::Ref(ref_pat, _) = filter_param.pat.kind {
2999+
(ref_pat, true)
3000+
} else {
3001+
(filter_param.pat, false)
3002+
};
3003+
// closure ends with is_some() or is_ok()
3004+
if let PatKind::Binding(_, filter_param_id, _, None) = filter_pat.kind;
3005+
if let ExprKind::MethodCall(path, _, [filter_arg], _) = filter_body.value.kind;
3006+
if let Some(opt_ty) = cx.typeck_results().expr_ty(filter_arg).ty_adt_def();
3007+
if let Some(is_result) = if cx.tcx.is_diagnostic_item(sym::option_type, opt_ty.did) {
3008+
Some(false)
3009+
} else if cx.tcx.is_diagnostic_item(sym::result_type, opt_ty.did) {
3010+
Some(true)
3011+
} else {
3012+
None
3013+
};
3014+
if path.ident.name.as_str() == if is_result { "is_ok" } else { "is_some" };
3015+
3016+
// ...map(|x| ...unwrap())
3017+
if let ExprKind::Closure(_, _, map_body_id, ..) = map_arg.kind;
3018+
let map_body = cx.tcx.hir().body(map_body_id);
3019+
if let [map_param] = map_body.params;
3020+
if let PatKind::Binding(_, map_param_id, map_param_ident, None) = map_param.pat.kind;
3021+
// closure ends with expect() or unwrap()
3022+
if let ExprKind::MethodCall(seg, _, [map_arg, ..], _) = map_body.value.kind;
3023+
if matches!(seg.ident.name, sym::expect | sym::unwrap | sym::unwrap_or);
3024+
3025+
let eq_fallback = |a: &Expr<'_>, b: &Expr<'_>| {
3026+
// in `filter(|x| ..)`, replace `*x` with `x`
3027+
let a_path = if_chain! {
3028+
if !is_filter_param_ref;
3029+
if let ExprKind::Unary(UnOp::UnDeref, expr_path) = a.kind;
3030+
then { expr_path } else { a }
3031+
};
3032+
// let the filter closure arg and the map closure arg be equal
3033+
if_chain! {
3034+
if let ExprKind::Path(QPath::Resolved(None, a_path)) = a_path.kind;
3035+
if let ExprKind::Path(QPath::Resolved(None, b_path)) = b.kind;
3036+
if a_path.res == Res::Local(filter_param_id);
3037+
if b_path.res == Res::Local(map_param_id);
3038+
if TyS::same_type(cx.typeck_results().expr_ty_adjusted(a), cx.typeck_results().expr_ty_adjusted(b));
3039+
then {
3040+
return true;
3041+
}
3042+
}
3043+
false
3044+
};
3045+
if SpanlessEq::new(cx).expr_fallback(eq_fallback).eq_expr(filter_arg, map_arg);
3046+
then {
3047+
let span = filter_span.to(map_span);
3048+
let msg = "`filter(..).map(..)` can be simplified as `filter_map(..)`";
3049+
let to_opt = if is_result { ".ok()" } else { "" };
3050+
let sugg = format!("filter_map(|{}| {}{})", map_param_ident, snippet(cx, map_arg.span, ".."), to_opt);
3051+
span_lint_and_sugg(cx, MANUAL_FILTER_MAP, span, msg, "try", sugg, Applicability::MachineApplicable);
3052+
}
29703053
}
29713054
}
29723055

tests/ui/filter_methods.stderr

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,3 @@
1-
error: called `filter(..).map(..)` on an `Iterator`
2-
--> $DIR/filter_methods.rs:6:21
3-
|
4-
LL | let _: Vec<_> = vec![5; 6].into_iter().filter(|&x| x == 0).map(|x| x * 2).collect();
5-
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6-
|
7-
= note: `-D clippy::filter-map` implied by `-D warnings`
8-
= help: this is more succinctly expressed by calling `.filter_map(..)` instead
9-
101
error: called `filter(..).flat_map(..)` on an `Iterator`
112
--> $DIR/filter_methods.rs:8:21
123
|
@@ -17,6 +8,7 @@ LL | | .filter(|&x| x == 0)
178
LL | | .flat_map(|x| x.checked_mul(2))
189
| |_______________________________________^
1910
|
11+
= note: `-D clippy::filter-map` implied by `-D warnings`
2012
= help: this is more succinctly expressed by calling `.flat_map(..)` and filtering by returning `iter::empty()`
2113

2214
error: called `filter_map(..).flat_map(..)` on an `Iterator`
@@ -43,5 +35,5 @@ LL | | .map(|x| x.checked_mul(2))
4335
|
4436
= help: this is more succinctly expressed by only calling `.filter_map(..)` instead
4537

46-
error: aborting due to 4 previous errors
38+
error: aborting due to 3 previous errors
4739

tests/ui/manual_filter_map.fixed

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// run-rustfix
2+
#![allow(dead_code)]
3+
#![warn(clippy::manual_filter_map)]
4+
#![allow(clippy::redundant_closure)] // FIXME suggestion may have redundant closure
5+
6+
fn main() {
7+
// is_some(), unwrap()
8+
let _ = (0..).filter_map(|a| to_opt(a));
9+
10+
// ref pattern, expect()
11+
let _ = (0..).filter_map(|a| to_opt(a));
12+
13+
// is_ok(), unwrap_or()
14+
let _ = (0..).filter_map(|a| to_res(a).ok());
15+
}
16+
17+
fn no_lint() {
18+
// no shared code
19+
let _ = (0..).filter(|n| *n > 1).map(|n| n + 1);
20+
21+
// very close but different since filter() provides a reference
22+
let _ = (0..).filter(|n| to_opt(n).is_some()).map(|a| to_opt(a).unwrap());
23+
24+
// similar but different
25+
let _ = (0..).filter(|n| to_opt(n).is_some()).map(|n| to_res(n).unwrap());
26+
let _ = (0..)
27+
.filter(|n| to_opt(n).map(|n| n + 1).is_some())
28+
.map(|a| to_opt(a).unwrap());
29+
}
30+
31+
fn to_opt<T>(_: T) -> Option<T> {
32+
unimplemented!()
33+
}
34+
35+
fn to_res<T>(_: T) -> Result<T, ()> {
36+
unimplemented!()
37+
}

tests/ui/manual_filter_map.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// run-rustfix
2+
#![allow(dead_code)]
3+
#![warn(clippy::manual_filter_map)]
4+
#![allow(clippy::redundant_closure)] // FIXME suggestion may have redundant closure
5+
6+
fn main() {
7+
// is_some(), unwrap()
8+
let _ = (0..).filter(|n| to_opt(*n).is_some()).map(|a| to_opt(a).unwrap());
9+
10+
// ref pattern, expect()
11+
let _ = (0..).filter(|&n| to_opt(n).is_some()).map(|a| to_opt(a).expect("hi"));
12+
13+
// is_ok(), unwrap_or()
14+
let _ = (0..).filter(|&n| to_res(n).is_ok()).map(|a| to_res(a).unwrap_or(1));
15+
}
16+
17+
fn no_lint() {
18+
// no shared code
19+
let _ = (0..).filter(|n| *n > 1).map(|n| n + 1);
20+
21+
// very close but different since filter() provides a reference
22+
let _ = (0..).filter(|n| to_opt(n).is_some()).map(|a| to_opt(a).unwrap());
23+
24+
// similar but different
25+
let _ = (0..).filter(|n| to_opt(n).is_some()).map(|n| to_res(n).unwrap());
26+
let _ = (0..)
27+
.filter(|n| to_opt(n).map(|n| n + 1).is_some())
28+
.map(|a| to_opt(a).unwrap());
29+
}
30+
31+
fn to_opt<T>(_: T) -> Option<T> {
32+
unimplemented!()
33+
}
34+
35+
fn to_res<T>(_: T) -> Result<T, ()> {
36+
unimplemented!()
37+
}

tests/ui/manual_filter_map.stderr

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
error: `filter(..).map(..)` can be simplified as `filter_map(..)`
2+
--> $DIR/manual_filter_map.rs:8:19
3+
|
4+
LL | let _ = (0..).filter(|n| to_opt(*n).is_some()).map(|a| to_opt(a).unwrap());
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `filter_map(|a| to_opt(a))`
6+
|
7+
= note: `-D clippy::manual-filter-map` implied by `-D warnings`
8+
9+
error: `filter(..).map(..)` can be simplified as `filter_map(..)`
10+
--> $DIR/manual_filter_map.rs:11:19
11+
|
12+
LL | let _ = (0..).filter(|&n| to_opt(n).is_some()).map(|a| to_opt(a).expect("hi"));
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `filter_map(|a| to_opt(a))`
14+
15+
error: `filter(..).map(..)` can be simplified as `filter_map(..)`
16+
--> $DIR/manual_filter_map.rs:14:19
17+
|
18+
LL | let _ = (0..).filter(|&n| to_res(n).is_ok()).map(|a| to_res(a).unwrap_or(1));
19+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `filter_map(|a| to_res(a).ok())`
20+
21+
error: aborting due to 3 previous errors
22+

0 commit comments

Comments
 (0)