@@ -17,6 +17,7 @@ mod filter_map_identity;
1717mod filter_map_next;
1818mod filter_next;
1919mod flat_map_identity;
20+ mod flat_map_option;
2021mod from_iter_instead_of_collect;
2122mod get_unwrap;
2223mod implicit_clone;
@@ -97,6 +98,29 @@ declare_clippy_lint! {
9798 "used `cloned` where `copied` could be used instead"
9899}
99100
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+
100124declare_clippy_lint ! {
101125 /// **What it does:** Checks for `.unwrap()` calls on `Option`s and on `Result`s.
102126 ///
@@ -1663,6 +1687,7 @@ impl_lint_pass!(Methods => [
16631687 CLONE_ON_REF_PTR ,
16641688 CLONE_DOUBLE_REF ,
16651689 CLONED_INSTEAD_OF_COPIED ,
1690+ FLAT_MAP_OPTION ,
16661691 INEFFICIENT_TO_STRING ,
16671692 NEW_RET_NO_SELF ,
16681693 SINGLE_CHAR_PATTERN ,
@@ -1958,7 +1983,10 @@ fn check_methods<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, msrv: Optio
19581983 unnecessary_filter_map:: check ( cx, expr, arg) ;
19591984 filter_map_identity:: check ( cx, expr, arg, span) ;
19601985 } ,
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+ } ,
19621990 ( "flatten" , [ ] ) => {
19631991 if let Some ( ( "map" , [ recv, map_arg] , _) ) = method_call ! ( recv) {
19641992 map_flatten:: check ( cx, expr, recv, map_arg) ;
0 commit comments