Skip to content

Add lint unnecessary_option_map_or_else #14662

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6292,6 +6292,7 @@ Released 2018-09-13
[`unnecessary_min_or_max`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_min_or_max
[`unnecessary_mut_passed`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_mut_passed
[`unnecessary_operation`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_operation
[`unnecessary_option_map_or_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_option_map_or_else
[`unnecessary_owned_empty_strings`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_owned_empty_strings
[`unnecessary_result_map_or_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_result_map_or_else
[`unnecessary_safety_comment`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_safety_comment
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/declared_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,7 @@ pub static LINTS: &[&crate::LintInfo] = &[
crate::methods::UNNECESSARY_LITERAL_UNWRAP_INFO,
crate::methods::UNNECESSARY_MAP_OR_INFO,
crate::methods::UNNECESSARY_MIN_OR_MAX_INFO,
crate::methods::UNNECESSARY_OPTION_MAP_OR_ELSE_INFO,
crate::methods::UNNECESSARY_RESULT_MAP_OR_ELSE_INFO,
crate::methods::UNNECESSARY_SORT_BY_INFO,
crate::methods::UNNECESSARY_TO_OWNED_INFO,
Expand Down
28 changes: 28 additions & 0 deletions clippy_lints/src/methods/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ mod unnecessary_lazy_eval;
mod unnecessary_literal_unwrap;
mod unnecessary_map_or;
mod unnecessary_min_or_max;
mod unnecessary_option_map_or_else;
mod unnecessary_result_map_or_else;
mod unnecessary_sort_by;
mod unnecessary_to_owned;
Expand Down Expand Up @@ -4529,6 +4530,31 @@ declare_clippy_lint! {
"detect swap with a temporary value"
}

declare_clippy_lint! {
/// ### What it does
/// Checks for usage of `.map_or_else()` "map closure" for `Option` type.
///
/// ### Why is this bad?
/// This can be written more concisely by using `unwrap_or_else()`.
///
/// ### Example
/// ```no_run
/// let k = 10;
/// let x: Option<u32> = Some(4);
/// let y = x.map_or_else(|| 2 * k, |n| n);
/// ```
/// Use instead:
/// ```no_run
/// let k = 10;
/// let x: Option<u32> = Some(4);
/// let y = x.unwrap_or_else(|| 2 * k);
/// ```
#[clippy::version = "1.88.0"]
pub UNNECESSARY_OPTION_MAP_OR_ELSE,
suspicious,
"making no use of the \"map closure\" when calling `.map_or_else(|| 2 * k, |n| n)`"
}

#[expect(clippy::struct_excessive_bools)]
pub struct Methods {
avoid_breaking_exported_api: bool,
Expand Down Expand Up @@ -4707,6 +4733,7 @@ impl_lint_pass!(Methods => [
MANUAL_CONTAINS,
IO_OTHER_ERROR,
SWAP_WITH_TEMPORARY,
UNNECESSARY_OPTION_MAP_OR_ELSE,
]);

/// Extracts a method call name, args, and `Span` of the method name.
Expand Down Expand Up @@ -5262,6 +5289,7 @@ impl Methods {
},
("map_or_else", [def, map]) => {
result_map_or_else_none::check(cx, expr, recv, def, map);
unnecessary_option_map_or_else::check(cx, expr, recv, def, map);
unnecessary_result_map_or_else::check(cx, expr, recv, def, map);
},
("next", []) => {
Expand Down
73 changes: 73 additions & 0 deletions clippy_lints/src/methods/unnecessary_option_map_or_else.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::peel_blocks;
use clippy_utils::source::snippet;
use clippy_utils::ty::is_type_diagnostic_item;
use rustc_errors::Applicability;
use rustc_hir::{Closure, Expr, ExprKind, HirId, QPath};
use rustc_lint::LateContext;
use rustc_span::symbol::sym;

use super::UNNECESSARY_OPTION_MAP_OR_ELSE;
use super::utils::get_last_chain_binding_hir_id;

fn emit_lint(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, def_arg: &Expr<'_>) {
let msg = "unused \"map closure\" when calling `Option::map_or_else` value";
let self_snippet = snippet(cx, recv.span, "..");
let err_snippet = snippet(cx, def_arg.span, "..");
span_lint_and_sugg(
cx,
UNNECESSARY_OPTION_MAP_OR_ELSE,
expr.span,
msg,
"consider using `unwrap_or_else`",
format!("{self_snippet}.unwrap_or_else({err_snippet})"),
Applicability::MachineApplicable,
);
}

fn handle_qpath(
cx: &LateContext<'_>,
expr: &Expr<'_>,
recv: &Expr<'_>,
def_arg: &Expr<'_>,
expected_hir_id: HirId,
qpath: QPath<'_>,
) {
if let QPath::Resolved(_, path) = qpath
&& let rustc_hir::def::Res::Local(hir_id) = path.res
&& expected_hir_id == hir_id
{
emit_lint(cx, expr, recv, def_arg);
}
}

/// lint use of `_.map_or_else(|err| err, |n| n)` for `Option`s.
pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, def_arg: &Expr<'_>, map_arg: &Expr<'_>) {
// lint if the caller of `map_or_else()` is an `Option`
if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::Option)
&& let ExprKind::Closure(&Closure { body, .. }) = map_arg.kind
&& let body = cx.tcx.hir_body(body)
&& let Some(first_param) = body.params.first()
{
let body_expr = peel_blocks(body.value);

match body_expr.kind {
ExprKind::Path(qpath) => {
handle_qpath(cx, expr, recv, def_arg, first_param.pat.hir_id, qpath);
},
// If this is a block (that wasn't peeled off), then it means there are statements.
ExprKind::Block(block, _) => {
if let Some(block_expr) = block.expr
// First we ensure that this is a "binding chain" (each statement is a binding
// of the previous one) and that it is a binding of the closure argument.
&& let Some(last_chain_binding_id) =
get_last_chain_binding_hir_id(first_param.pat.hir_id, block.stmts)
&& let ExprKind::Path(qpath) = block_expr.kind
{
handle_qpath(cx, expr, recv, def_arg, last_chain_binding_id, qpath);
}
},
_ => {},
}
}
}
3 changes: 2 additions & 1 deletion tests/ui/option_if_let_else.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
clippy::redundant_locals,
clippy::manual_midpoint,
clippy::manual_unwrap_or_default,
clippy::manual_unwrap_or
clippy::manual_unwrap_or,
clippy::unnecessary_option_map_or_else
)]

fn bad1(string: Option<&str>) -> (bool, &str) {
Expand Down
3 changes: 2 additions & 1 deletion tests/ui/option_if_let_else.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
clippy::redundant_locals,
clippy::manual_midpoint,
clippy::manual_unwrap_or_default,
clippy::manual_unwrap_or
clippy::manual_unwrap_or,
clippy::unnecessary_option_map_or_else
)]

fn bad1(string: Option<&str>) -> (bool, &str) {
Expand Down
50 changes: 25 additions & 25 deletions tests/ui/option_if_let_else.stderr
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:13:5
--> tests/ui/option_if_let_else.rs:14:5
|
LL | / if let Some(x) = string {
LL | |
Expand All @@ -13,19 +13,19 @@ LL | | }
= help: to override `-D warnings` add `#[allow(clippy::option_if_let_else)]`

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:32:13
--> tests/ui/option_if_let_else.rs:33:13
|
LL | let _ = if let Some(s) = *string { s.len() } else { 0 };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `string.map_or(0, |s| s.len())`

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:34:13
--> tests/ui/option_if_let_else.rs:35:13
|
LL | let _ = if let Some(s) = &num { s } else { &0 };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `num.as_ref().map_or(&0, |s| s)`

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:36:13
--> tests/ui/option_if_let_else.rs:37:13
|
LL | let _ = if let Some(s) = &mut num {
| _____________^
Expand All @@ -47,13 +47,13 @@ LL ~ });
|

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:43:13
--> tests/ui/option_if_let_else.rs:44:13
|
LL | let _ = if let Some(ref s) = num { s } else { &0 };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `num.as_ref().map_or(&0, |s| s)`

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:45:13
--> tests/ui/option_if_let_else.rs:46:13
|
LL | let _ = if let Some(mut s) = num {
| _____________^
Expand All @@ -75,7 +75,7 @@ LL ~ });
|

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:52:13
--> tests/ui/option_if_let_else.rs:53:13
|
LL | let _ = if let Some(ref mut s) = num {
| _____________^
Expand All @@ -97,7 +97,7 @@ LL ~ });
|

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:62:5
--> tests/ui/option_if_let_else.rs:63:5
|
LL | / if let Some(x) = arg {
LL | |
Expand All @@ -118,7 +118,7 @@ LL + })
|

error: use Option::map_or_else instead of an if let/else
--> tests/ui/option_if_let_else.rs:76:13
--> tests/ui/option_if_let_else.rs:77:13
|
LL | let _ = if let Some(x) = arg {
| _____________^
Expand All @@ -131,7 +131,7 @@ LL | | };
| |_____^ help: try: `arg.map_or_else(side_effect, |x| x)`

error: use Option::map_or_else instead of an if let/else
--> tests/ui/option_if_let_else.rs:86:13
--> tests/ui/option_if_let_else.rs:87:13
|
LL | let _ = if let Some(x) = arg {
| _____________^
Expand All @@ -154,7 +154,7 @@ LL ~ }, |x| x * x * x * x);
|

error: use Option::map_or_else instead of an if let/else
--> tests/ui/option_if_let_else.rs:120:13
--> tests/ui/option_if_let_else.rs:121:13
|
LL | / if let Some(idx) = s.find('.') {
LL | |
Expand All @@ -165,7 +165,7 @@ LL | | }
| |_____________^ help: try: `s.find('.').map_or_else(|| vec![s.to_string()], |idx| vec![s[..idx].to_string(), s[idx..].to_string()])`

error: use Option::map_or_else instead of an if let/else
--> tests/ui/option_if_let_else.rs:132:5
--> tests/ui/option_if_let_else.rs:133:5
|
LL | / if let Ok(binding) = variable {
LL | |
Expand All @@ -189,13 +189,13 @@ LL + })
|

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:157:13
--> tests/ui/option_if_let_else.rs:158:13
|
LL | let _ = if let Some(x) = optional { x + 2 } else { 5 };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `optional.map_or(5, |x| x + 2)`

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:168:13
--> tests/ui/option_if_let_else.rs:169:13
|
LL | let _ = if let Some(x) = Some(0) {
| _____________^
Expand All @@ -217,13 +217,13 @@ LL ~ });
|

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:197:13
--> tests/ui/option_if_let_else.rs:198:13
|
LL | let _ = if let Some(x) = Some(0) { s.len() + x } else { s.len() };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Some(0).map_or(s.len(), |x| s.len() + x)`

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:202:13
--> tests/ui/option_if_let_else.rs:203:13
|
LL | let _ = if let Some(x) = Some(0) {
| _____________^
Expand All @@ -245,7 +245,7 @@ LL ~ });
|

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:242:13
--> tests/ui/option_if_let_else.rs:243:13
|
LL | let _ = match s {
| _____________^
Expand All @@ -256,7 +256,7 @@ LL | | };
| |_____^ help: try: `s.map_or(1, |string| string.len())`

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:247:13
--> tests/ui/option_if_let_else.rs:248:13
|
LL | let _ = match Some(10) {
| _____________^
Expand All @@ -267,7 +267,7 @@ LL | | };
| |_____^ help: try: `Some(10).map_or(5, |a| a + 1)`

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:254:13
--> tests/ui/option_if_let_else.rs:255:13
|
LL | let _ = match res {
| _____________^
Expand All @@ -278,7 +278,7 @@ LL | | };
| |_____^ help: try: `res.map_or(1, |a| a + 1)`

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:259:13
--> tests/ui/option_if_let_else.rs:260:13
|
LL | let _ = match res {
| _____________^
Expand All @@ -289,13 +289,13 @@ LL | | };
| |_____^ help: try: `res.map_or(1, |a| a + 1)`

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:264:13
--> tests/ui/option_if_let_else.rs:265:13
|
LL | let _ = if let Ok(a) = res { a + 1 } else { 5 };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `res.map_or(5, |a| a + 1)`

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:282:17
--> tests/ui/option_if_let_else.rs:283:17
|
LL | let _ = match initial {
| _________________^
Expand All @@ -306,7 +306,7 @@ LL | | };
| |_________^ help: try: `initial.as_ref().map_or(42, |value| do_something(value))`

error: use Option::map_or instead of an if let/else
--> tests/ui/option_if_let_else.rs:290:17
--> tests/ui/option_if_let_else.rs:291:17
|
LL | let _ = match initial {
| _________________^
Expand All @@ -317,7 +317,7 @@ LL | | };
| |_________^ help: try: `initial.as_mut().map_or(42, |value| do_something2(value))`

error: use Option::map_or_else instead of an if let/else
--> tests/ui/option_if_let_else.rs:314:24
--> tests/ui/option_if_let_else.rs:315:24
|
LL | let mut _hashmap = if let Some(hm) = &opt {
| ________________________^
Expand All @@ -329,7 +329,7 @@ LL | | };
| |_____^ help: try: `opt.as_ref().map_or_else(HashMap::new, |hm| hm.clone())`

error: use Option::map_or_else instead of an if let/else
--> tests/ui/option_if_let_else.rs:321:19
--> tests/ui/option_if_let_else.rs:322:19
|
LL | let mut _hm = if let Some(hm) = &opt { hm.clone() } else { new_map!() };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `opt.as_ref().map_or_else(|| new_map!(), |hm| hm.clone())`
Expand Down
1 change: 1 addition & 0 deletions tests/ui/or_fun_call.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
clippy::uninlined_format_args,
clippy::unnecessary_wraps,
clippy::unnecessary_literal_unwrap,
clippy::unnecessary_option_map_or_else,
clippy::useless_vec
)]

Expand Down
1 change: 1 addition & 0 deletions tests/ui/or_fun_call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
clippy::uninlined_format_args,
clippy::unnecessary_wraps,
clippy::unnecessary_literal_unwrap,
clippy::unnecessary_option_map_or_else,
clippy::useless_vec
)]

Expand Down
Loading
Loading