Skip to content

Commit 9020937

Browse files
committed
Auto merge of rust-lang#11030 - darklyspaced:master, r=Centri3,xFrednet
suggests `is_some_and` over `map().unwrap` changelog: Enhancement: [`option_map_unwrap_or`] now considers the [`msrv`] config when creating the suggestion. * modified option_map_unwrap_or lint to recognise when an `Option<T>` is mapped to an `Option<bool>` with false being used when `None` is detected; suggests the use of `is_some_and` instead * msrv is set to 1.70.0 for this lint; when `is_some_and` was stabilised fixes rust-lang#9125
2 parents 10ce1a6 + bb42b18 commit 9020937

File tree

7 files changed

+89
-9
lines changed

7 files changed

+89
-9
lines changed

book/src/lint_configuration.md

+1
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ The minimum rust version that the project supports
108108
* [`manual_str_repeat`](https://rust-lang.github.io/rust-clippy/master/index.html#manual_str_repeat)
109109
* [`cloned_instead_of_copied`](https://rust-lang.github.io/rust-clippy/master/index.html#cloned_instead_of_copied)
110110
* [`redundant_field_names`](https://rust-lang.github.io/rust-clippy/master/index.html#redundant_field_names)
111+
* [`option_map_unwrap_or`](https://rust-lang.github.io/rust-clippy/master/index.html#option_map_unwrap_or)
111112
* [`redundant_static_lifetimes`](https://rust-lang.github.io/rust-clippy/master/index.html#redundant_static_lifetimes)
112113
* [`filter_map_next`](https://rust-lang.github.io/rust-clippy/master/index.html#filter_map_next)
113114
* [`checked_conversions`](https://rust-lang.github.io/rust-clippy/master/index.html#checked_conversions)

clippy_lints/src/methods/mod.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,7 @@ declare_clippy_lint! {
513513
/// # let result: Result<usize, ()> = Ok(1);
514514
/// # fn some_function(foo: ()) -> usize { 1 }
515515
/// option.map(|a| a + 1).unwrap_or(0);
516+
/// option.map(|a| a > 10).unwrap_or(false);
516517
/// result.map(|a| a + 1).unwrap_or_else(some_function);
517518
/// ```
518519
///
@@ -522,6 +523,7 @@ declare_clippy_lint! {
522523
/// # let result: Result<usize, ()> = Ok(1);
523524
/// # fn some_function(foo: ()) -> usize { 1 }
524525
/// option.map_or(0, |a| a + 1);
526+
/// option.is_some_and(|a| a > 10);
525527
/// result.map_or_else(some_function, |a| a + 1);
526528
/// ```
527529
#[clippy::version = "1.45.0"]
@@ -3904,7 +3906,7 @@ impl Methods {
39043906
manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
39053907
},
39063908
Some(("map", m_recv, [m_arg], span, _)) => {
3907-
option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
3909+
option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span, &self.msrv);
39083910
},
39093911
Some(("then_some", t_recv, [t_arg], _, _)) => {
39103912
obfuscated_if_else::check(cx, expr, t_recv, t_arg, u_arg);

clippy_lints/src/methods/option_map_unwrap_or.rs

+25-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use clippy_utils::diagnostics::span_lint_and_then;
2+
use clippy_utils::msrvs::{self, Msrv};
23
use clippy_utils::source::snippet_with_applicability;
34
use clippy_utils::ty::is_copy;
45
use clippy_utils::ty::is_type_diagnostic_item;
@@ -19,6 +20,7 @@ use rustc_span::sym;
1920
use super::MAP_UNWRAP_OR;
2021

2122
/// lint use of `map().unwrap_or()` for `Option`s
23+
#[expect(clippy::too_many_arguments)]
2224
pub(super) fn check<'tcx>(
2325
cx: &LateContext<'tcx>,
2426
expr: &rustc_hir::Expr<'_>,
@@ -27,6 +29,7 @@ pub(super) fn check<'tcx>(
2729
unwrap_recv: &rustc_hir::Expr<'_>,
2830
unwrap_arg: &'tcx rustc_hir::Expr<'_>,
2931
map_span: Span,
32+
msrv: &Msrv,
3033
) {
3134
// lint if the caller of `map()` is an `Option`
3235
if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::Option) {
@@ -74,16 +77,29 @@ pub(super) fn check<'tcx>(
7477
return;
7578
}
7679

80+
// is_some_and is stabilised && `unwrap_or` argument is false; suggest `is_some_and` instead
81+
let suggest_is_some_and = msrv.meets(msrvs::OPTION_IS_SOME_AND)
82+
&& matches!(&unwrap_arg.kind, ExprKind::Lit(lit)
83+
if matches!(lit.node, rustc_ast::LitKind::Bool(false)));
84+
7785
let mut applicability = Applicability::MachineApplicable;
7886
// get snippet for unwrap_or()
7987
let unwrap_snippet = snippet_with_applicability(cx, unwrap_arg.span, "..", &mut applicability);
8088
// lint message
8189
// comparing the snippet from source to raw text ("None") below is safe
8290
// because we already have checked the type.
83-
let arg = if unwrap_snippet == "None" { "None" } else { "<a>" };
91+
let arg = if unwrap_snippet == "None" {
92+
"None"
93+
} else if suggest_is_some_and {
94+
"false"
95+
} else {
96+
"<a>"
97+
};
8498
let unwrap_snippet_none = unwrap_snippet == "None";
8599
let suggest = if unwrap_snippet_none {
86100
"and_then(<f>)"
101+
} else if suggest_is_some_and {
102+
"is_some_and(<f>)"
87103
} else {
88104
"map_or(<a>, <f>)"
89105
};
@@ -98,12 +114,18 @@ pub(super) fn check<'tcx>(
98114
let mut suggestion = vec![
99115
(
100116
map_span,
101-
String::from(if unwrap_snippet_none { "and_then" } else { "map_or" }),
117+
String::from(if unwrap_snippet_none {
118+
"and_then"
119+
} else if suggest_is_some_and {
120+
"is_some_and"
121+
} else {
122+
"map_or"
123+
}),
102124
),
103125
(expr.span.with_lo(unwrap_recv.span.hi()), String::new()),
104126
];
105127

106-
if !unwrap_snippet_none {
128+
if !unwrap_snippet_none && !suggest_is_some_and {
107129
suggestion.push((map_arg_span.with_hi(map_arg_span.lo()), format!("{unwrap_snippet}, ")));
108130
}
109131

clippy_lints/src/utils/conf.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,7 @@ define_Conf! {
294294
///
295295
/// Suppress lints whenever the suggested change would cause breakage for other crates.
296296
(avoid_breaking_exported_api: bool = true),
297-
/// Lint: MANUAL_SPLIT_ONCE, MANUAL_STR_REPEAT, CLONED_INSTEAD_OF_COPIED, REDUNDANT_FIELD_NAMES, REDUNDANT_STATIC_LIFETIMES, FILTER_MAP_NEXT, CHECKED_CONVERSIONS, MANUAL_RANGE_CONTAINS, USE_SELF, MEM_REPLACE_WITH_DEFAULT, MANUAL_NON_EXHAUSTIVE, OPTION_AS_REF_DEREF, MAP_UNWRAP_OR, MATCH_LIKE_MATCHES_MACRO, MANUAL_STRIP, MISSING_CONST_FOR_FN, UNNESTED_OR_PATTERNS, FROM_OVER_INTO, PTR_AS_PTR, IF_THEN_SOME_ELSE_NONE, APPROX_CONSTANT, DEPRECATED_CFG_ATTR, INDEX_REFUTABLE_SLICE, MAP_CLONE, BORROW_AS_PTR, MANUAL_BITS, ERR_EXPECT, CAST_ABS_TO_UNSIGNED, UNINLINED_FORMAT_ARGS, MANUAL_CLAMP, MANUAL_LET_ELSE, UNCHECKED_DURATION_SUBTRACTION, COLLAPSIBLE_STR_REPLACE, SEEK_FROM_CURRENT, SEEK_REWIND, UNNECESSARY_LAZY_EVALUATIONS, TRANSMUTE_PTR_TO_REF, ALMOST_COMPLETE_RANGE, NEEDLESS_BORROW, DERIVABLE_IMPLS, MANUAL_IS_ASCII_CHECK, MANUAL_REM_EUCLID, MANUAL_RETAIN, TYPE_REPETITION_IN_BOUNDS.
297+
/// Lint: MANUAL_SPLIT_ONCE, MANUAL_STR_REPEAT, CLONED_INSTEAD_OF_COPIED, REDUNDANT_FIELD_NAMES, OPTION_MAP_UNWRAP_OR, REDUNDANT_STATIC_LIFETIMES, FILTER_MAP_NEXT, CHECKED_CONVERSIONS, MANUAL_RANGE_CONTAINS, USE_SELF, MEM_REPLACE_WITH_DEFAULT, MANUAL_NON_EXHAUSTIVE, OPTION_AS_REF_DEREF, MAP_UNWRAP_OR, MATCH_LIKE_MATCHES_MACRO, MANUAL_STRIP, MISSING_CONST_FOR_FN, UNNESTED_OR_PATTERNS, FROM_OVER_INTO, PTR_AS_PTR, IF_THEN_SOME_ELSE_NONE, APPROX_CONSTANT, DEPRECATED_CFG_ATTR, INDEX_REFUTABLE_SLICE, MAP_CLONE, BORROW_AS_PTR, MANUAL_BITS, ERR_EXPECT, CAST_ABS_TO_UNSIGNED, UNINLINED_FORMAT_ARGS, MANUAL_CLAMP, MANUAL_LET_ELSE, UNCHECKED_DURATION_SUBTRACTION, COLLAPSIBLE_STR_REPLACE, SEEK_FROM_CURRENT, SEEK_REWIND, UNNECESSARY_LAZY_EVALUATIONS, TRANSMUTE_PTR_TO_REF, ALMOST_COMPLETE_RANGE, NEEDLESS_BORROW, DERIVABLE_IMPLS, MANUAL_IS_ASCII_CHECK, MANUAL_REM_EUCLID, MANUAL_RETAIN, TYPE_REPETITION_IN_BOUNDS.
298298
///
299299
/// The minimum rust version that the project supports
300300
(msrv: Option<String> = None),

clippy_utils/src/msrvs.rs

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ macro_rules! msrv_aliases {
1919

2020
// names may refer to stabilized feature flags or library items
2121
msrv_aliases! {
22+
1,70,0 { OPTION_IS_SOME_AND }
2223
1,68,0 { PATH_MAIN_SEPARATOR_STR }
2324
1,65,0 { LET_ELSE, POINTER_CAST_CONSTNESS }
2425
1,62,0 { BOOL_THEN_SOME, DEFAULT_ENUM_ATTRIBUTE }

tests/ui/map_unwrap_or.rs

+18
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,10 @@ fn option_methods() {
5656
.unwrap_or_else(||
5757
0
5858
);
59+
60+
// Check for `map(f).unwrap_or(false)` use.
61+
let _ = opt.map(|x| x > 5).unwrap_or(false);
62+
5963
}
6064

6165
#[rustfmt::skip]
@@ -95,6 +99,20 @@ fn msrv_1_41() {
9599
let _ = res.map(|x| x + 1).unwrap_or_else(|_e| 0);
96100
}
97101

102+
#[clippy::msrv = "1.69"]
103+
fn msrv_1_69() {
104+
let opt: Option<i32> = Some(1);
105+
106+
let _ = opt.map(|x| x > 5).unwrap_or(false);
107+
}
108+
109+
#[clippy::msrv = "1.70"]
110+
fn msrv_1_70() {
111+
let opt: Option<i32> = Some(1);
112+
113+
let _ = opt.map(|x| x > 5).unwrap_or(false);
114+
}
115+
98116
mod issue_10579 {
99117
// Different variations of the same issue.
100118
fn v1() {

tests/ui/map_unwrap_or.stderr

+40-4
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,20 @@ LL | | 0
126126
LL | | );
127127
| |_________^
128128

129+
error: called `map(<f>).unwrap_or(false)` on an `Option` value. This can be done more directly by calling `is_some_and(<f>)` instead
130+
--> $DIR/map_unwrap_or.rs:61:13
131+
|
132+
LL | let _ = opt.map(|x| x > 5).unwrap_or(false);
133+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
134+
|
135+
help: use `is_some_and(<f>)` instead
136+
|
137+
LL - let _ = opt.map(|x| x > 5).unwrap_or(false);
138+
LL + let _ = opt.is_some_and(|x| x > 5);
139+
|
140+
129141
error: called `map(<f>).unwrap_or_else(<g>)` on a `Result` value. This can be done more directly by calling `.map_or_else(<g>, <f>)` instead
130-
--> $DIR/map_unwrap_or.rs:67:13
142+
--> $DIR/map_unwrap_or.rs:71:13
131143
|
132144
LL | let _ = res.map(|x| {
133145
| _____________^
@@ -137,7 +149,7 @@ LL | | ).unwrap_or_else(|_e| 0);
137149
| |____________________________^
138150

139151
error: called `map(<f>).unwrap_or_else(<g>)` on a `Result` value. This can be done more directly by calling `.map_or_else(<g>, <f>)` instead
140-
--> $DIR/map_unwrap_or.rs:71:13
152+
--> $DIR/map_unwrap_or.rs:75:13
141153
|
142154
LL | let _ = res.map(|x| x + 1)
143155
| _____________^
@@ -147,10 +159,34 @@ LL | | });
147159
| |__________^
148160

149161
error: called `map(<f>).unwrap_or_else(<g>)` on a `Result` value. This can be done more directly by calling `.map_or_else(<g>, <f>)` instead
150-
--> $DIR/map_unwrap_or.rs:95:13
162+
--> $DIR/map_unwrap_or.rs:99:13
151163
|
152164
LL | let _ = res.map(|x| x + 1).unwrap_or_else(|_e| 0);
153165
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `res.map_or_else(|_e| 0, |x| x + 1)`
154166

155-
error: aborting due to 12 previous errors
167+
error: called `map(<f>).unwrap_or(<a>)` on an `Option` value. This can be done more directly by calling `map_or(<a>, <f>)` instead
168+
--> $DIR/map_unwrap_or.rs:106:13
169+
|
170+
LL | let _ = opt.map(|x| x > 5).unwrap_or(false);
171+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
172+
|
173+
help: use `map_or(<a>, <f>)` instead
174+
|
175+
LL - let _ = opt.map(|x| x > 5).unwrap_or(false);
176+
LL + let _ = opt.map_or(false, |x| x > 5);
177+
|
178+
179+
error: called `map(<f>).unwrap_or(false)` on an `Option` value. This can be done more directly by calling `is_some_and(<f>)` instead
180+
--> $DIR/map_unwrap_or.rs:113:13
181+
|
182+
LL | let _ = opt.map(|x| x > 5).unwrap_or(false);
183+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
184+
|
185+
help: use `is_some_and(<f>)` instead
186+
|
187+
LL - let _ = opt.map(|x| x > 5).unwrap_or(false);
188+
LL + let _ = opt.is_some_and(|x| x > 5);
189+
|
190+
191+
error: aborting due to 15 previous errors
156192

0 commit comments

Comments
 (0)