Skip to content
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

use of Result::unwrap_or_else over Result::map_or_else #7363

Closed
Closed
Show file tree
Hide file tree
Changes from 4 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 @@ -2735,6 +2735,7 @@ Released 2018-09-13
[`unused_unit`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_unit
[`unusual_byte_groupings`]: https://rust-lang.github.io/rust-clippy/master/index.html#unusual_byte_groupings
[`unwrap_in_result`]: https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_in_result
[`unwrap_or_else_over_map_or_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_or_else_over_map_or_else
[`unwrap_used`]: https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_used
[`upper_case_acronyms`]: https://rust-lang.github.io/rust-clippy/master/index.html#upper_case_acronyms
[`use_debug`]: https://rust-lang.github.io/rust-clippy/master/index.html#use_debug
Expand Down
5 changes: 5 additions & 0 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ mod unused_self;
mod unused_unit;
mod unwrap;
mod unwrap_in_result;
mod unwrap_or_else_over_map_or_else;
mod upper_case_acronyms;
mod use_self;
mod useless_conversion;
Expand Down Expand Up @@ -958,6 +959,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
unwrap::PANICKING_UNWRAP,
unwrap::UNNECESSARY_UNWRAP,
unwrap_in_result::UNWRAP_IN_RESULT,
unwrap_or_else_over_map_or_else::UNWRAP_OR_ELSE_OVER_MAP_OR_ELSE,
upper_case_acronyms::UPPER_CASE_ACRONYMS,
use_self::USE_SELF,
useless_conversion::USELESS_CONVERSION,
Expand Down Expand Up @@ -1127,6 +1129,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
LintId::of(unnested_or_patterns::UNNESTED_OR_PATTERNS),
LintId::of(unused_async::UNUSED_ASYNC),
LintId::of(unused_self::UNUSED_SELF),
LintId::of(unwrap_or_else_over_map_or_else::UNWRAP_OR_ELSE_OVER_MAP_OR_ELSE),
LintId::of(wildcard_imports::ENUM_GLOB_USE),
LintId::of(wildcard_imports::WILDCARD_IMPORTS),
LintId::of(zero_sized_map_values::ZERO_SIZED_MAP_VALUES),
Expand All @@ -1150,6 +1153,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:

store.register_group(true, "clippy::all", Some("clippy"), vec![
LintId::of(absurd_extreme_comparisons::ABSURD_EXTREME_COMPARISONS),
LintId::of(unwrap_or_else_over_map_or_else::UNWRAP_OR_ELSE_OVER_MAP_OR_ELSE),
LintId::of(approx_const::APPROX_CONSTANT),
LintId::of(assertions_on_constants::ASSERTIONS_ON_CONSTANTS),
LintId::of(assign_ops::ASSIGN_OP_PATTERN),
Expand Down Expand Up @@ -1873,6 +1877,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
store.register_late_pass(|| box size_of_in_element_count::SizeOfInElementCount);
store.register_late_pass(|| box map_clone::MapClone);
store.register_late_pass(|| box map_err_ignore::MapErrIgnore);
store.register_late_pass(|| box unwrap_or_else_over_map_or_else::UnwrapOrElseOverMapOrElse);
store.register_late_pass(|| box shadow::Shadow);
store.register_late_pass(|| box unit_types::UnitTypes);
store.register_late_pass(|| box loops::Loops);
Expand Down
68 changes: 68 additions & 0 deletions clippy_lints/src/unwrap_or_else_over_map_or_else.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
use clippy_utils::diagnostics::span_lint_and_help;
use if_chain::if_chain;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint_pass, declare_tool_lint};

declare_clippy_lint! {
/// **What it does:** Suggest the use of Result::unwrap_or_else over Result::map_or_else if map_or_else is just used to unpack a successful result while handling an error
///
/// **Why is this bad?** The unwrap_or_else is shorter and more descriptive
///
/// **Known problems:** None.
///
/// **Example:**
///
/// ```rust
/// // example code where clippy issues a warning
/// ```
/// func_result(in_num: u8) -> Result<&'static str, &'static str> {
/// if in_num % 2 != 0 {
/// return Err("Can't do this because input is odd...");
/// }
/// Ok("An even number :)")
/// }
///
/// func_result(2).map_or_else(|e| println!("{:?}", e), |n| println!("{}", n))
/// Use instead:
/// ```rust
/// // example code which does not raise clippy warning
/// /// let c= func_result(3).unwrap_or_else(|e| {
/// println!("Error: {:?}", e);
/// process::exit(1);
Valentine-Mario marked this conversation as resolved.
Show resolved Hide resolved
/// });
///
/// ```
pub UNWRAP_OR_ELSE_OVER_MAP_OR_ELSE,
pedantic,
"use 'Result::unwrap_or_else' over 'Result::map_or_else'"
}

declare_lint_pass!(UnwrapOrElseOverMapOrElse => [UNWRAP_OR_ELSE_OVER_MAP_OR_ELSE]);

impl LateLintPass<'_> for UnwrapOrElseOverMapOrElse {
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
if_chain! {
//check if this is a method call eg func.map_or_else()
if let ExprKind::MethodCall(method, t_span, args, _) = expr.kind;
//check if the function name is map_or_else
if method.ident.as_str() == "map_or_else";
//check if the first arg is a closure
if let ExprKind::Closure(_, _, body_id, _, _) = args[1].kind ;
//get closure body parameter
let closure_body = cx.tcx.hir().body(body_id);
//make sure it has a parameter of one
if closure_body.params.len() == 1;
then{
span_lint_and_help(
cx,
UNWRAP_OR_ELSE_OVER_MAP_OR_ELSE,
t_span,
"Result::unwrap_or_else is shorter and more succinet",
None,
"consider unwrap_or_else(|e| handle_the_error(e)) to unpack result",
);
}
}
}
}
17 changes: 17 additions & 0 deletions tests/ui/unwrap_or_else_over_map_or_else.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#![warn(clippy::unwrap_or_else_over_map_or_else)]
use std::process;

fn main() {
let c = func_result(3).unwrap_or_else(|e| {
println!("Error: {:?}", e);
process::exit(1);
});
func_result(2).map_or_else(|e| println!("{:?}", e), |n| println!("{}", n))
}

fn func_result(in_num: u8) -> Result<&'static str, &'static str> {
if in_num % 2 != 0 {
return Err("Can't do this because input is odd...");
}
Ok("An even number :)")
}
11 changes: 11 additions & 0 deletions tests/ui/unwrap_or_else_over_map_or_else.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
error: Result::unwrap_or_else is shorter and more succinet
--> $DIR/unwrap_or_else_over_map_or_else.rs:9:20
|
LL | func_result(2).map_or_else(|e| println!("{:?}", e), |n| println!("{}", n))
| ^^^^^^^^^^^
|
= note: `-D clippy::unwrap-or-else-over-map-or-else` implied by `-D warnings`
= help: consider unwrap_or_else(|e| handle_the_error(e)) to unpack result

error: aborting due to previous error