@@ -17,6 +17,7 @@ mod filter_map_identity;
17
17
mod filter_map_next;
18
18
mod filter_next;
19
19
mod flat_map_identity;
20
+ mod flat_map_option;
20
21
mod from_iter_instead_of_collect;
21
22
mod get_unwrap;
22
23
mod implicit_clone;
@@ -97,6 +98,29 @@ declare_clippy_lint! {
97
98
"used `cloned` where `copied` could be used instead"
98
99
}
99
100
101
+ declare_clippy_lint ! {
102
+ /// **What it does:** Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
103
+ /// used instead.
104
+ ///
105
+ /// **Why is this bad?** When applicable, `filter_map()` is more clear since it shows that
106
+ /// `Option` is used to produce 0 or 1 items.
107
+ ///
108
+ /// **Known problems:** None.
109
+ ///
110
+ /// **Example:**
111
+ ///
112
+ /// ```rust
113
+ /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
114
+ /// ```
115
+ /// Use instead:
116
+ /// ```rust
117
+ /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
118
+ /// ```
119
+ pub FLAT_MAP_OPTION ,
120
+ pedantic,
121
+ "used `flat_map` where `filter_map` could be used instead"
122
+ }
123
+
100
124
declare_clippy_lint ! {
101
125
/// **What it does:** Checks for `.unwrap()` calls on `Option`s and on `Result`s.
102
126
///
@@ -1663,6 +1687,7 @@ impl_lint_pass!(Methods => [
1663
1687
CLONE_ON_REF_PTR ,
1664
1688
CLONE_DOUBLE_REF ,
1665
1689
CLONED_INSTEAD_OF_COPIED ,
1690
+ FLAT_MAP_OPTION ,
1666
1691
INEFFICIENT_TO_STRING ,
1667
1692
NEW_RET_NO_SELF ,
1668
1693
SINGLE_CHAR_PATTERN ,
@@ -1958,7 +1983,10 @@ fn check_methods<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, msrv: Optio
1958
1983
unnecessary_filter_map:: check ( cx, expr, arg) ;
1959
1984
filter_map_identity:: check ( cx, expr, arg, span) ;
1960
1985
} ,
1961
- ( "flat_map" , [ flm_arg] ) => flat_map_identity:: check ( cx, expr, flm_arg, span) ,
1986
+ ( "flat_map" , [ arg] ) => {
1987
+ flat_map_identity:: check ( cx, expr, arg, span) ;
1988
+ flat_map_option:: check ( cx, expr, arg, span) ;
1989
+ } ,
1962
1990
( "flatten" , [ ] ) => {
1963
1991
if let Some ( ( "map" , [ recv, map_arg] , _) ) = method_call ! ( recv) {
1964
1992
map_flatten:: check ( cx, expr, recv, map_arg) ;
0 commit comments