Skip to content

Commit b337f9e

Browse files
committed
Merge ManualUnwrapOr into Matches lint pass
1 parent 81e4450 commit b337f9e

File tree

7 files changed

+120
-129
lines changed

7 files changed

+120
-129
lines changed

clippy_lints/src/lib.register_all.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,14 +136,14 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![
136136
LintId::of(manual_map::MANUAL_MAP),
137137
LintId::of(manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE),
138138
LintId::of(manual_strip::MANUAL_STRIP),
139-
LintId::of(manual_unwrap_or::MANUAL_UNWRAP_OR),
140139
LintId::of(map_clone::MAP_CLONE),
141140
LintId::of(map_unit_fn::OPTION_MAP_UNIT_FN),
142141
LintId::of(map_unit_fn::RESULT_MAP_UNIT_FN),
143142
LintId::of(match_result_ok::MATCH_RESULT_OK),
144143
LintId::of(match_str_case_mismatch::MATCH_STR_CASE_MISMATCH),
145144
LintId::of(matches::COLLAPSIBLE_MATCH),
146145
LintId::of(matches::INFALLIBLE_DESTRUCTURING_MATCH),
146+
LintId::of(matches::MANUAL_UNWRAP_OR),
147147
LintId::of(matches::MATCH_AS_REF),
148148
LintId::of(matches::MATCH_LIKE_MATCHES_MACRO),
149149
LintId::of(matches::MATCH_OVERLAPPING_ARM),

clippy_lints/src/lib.register_complexity.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,9 @@ store.register_group(true, "clippy::complexity", Some("clippy_complexity"), vec!
2525
LintId::of(loops::SINGLE_ELEMENT_LOOP),
2626
LintId::of(loops::WHILE_LET_LOOP),
2727
LintId::of(manual_strip::MANUAL_STRIP),
28-
LintId::of(manual_unwrap_or::MANUAL_UNWRAP_OR),
2928
LintId::of(map_unit_fn::OPTION_MAP_UNIT_FN),
3029
LintId::of(map_unit_fn::RESULT_MAP_UNIT_FN),
30+
LintId::of(matches::MANUAL_UNWRAP_OR),
3131
LintId::of(matches::MATCH_AS_REF),
3232
LintId::of(matches::MATCH_SINGLE_BINDING),
3333
LintId::of(matches::NEEDLESS_MATCH),

clippy_lints/src/lib.register_lints.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,6 @@ store.register_lints(&[
254254
manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE,
255255
manual_ok_or::MANUAL_OK_OR,
256256
manual_strip::MANUAL_STRIP,
257-
manual_unwrap_or::MANUAL_UNWRAP_OR,
258257
map_clone::MAP_CLONE,
259258
map_err_ignore::MAP_ERR_IGNORE,
260259
map_unit_fn::OPTION_MAP_UNIT_FN,
@@ -264,6 +263,7 @@ store.register_lints(&[
264263
match_str_case_mismatch::MATCH_STR_CASE_MISMATCH,
265264
matches::COLLAPSIBLE_MATCH,
266265
matches::INFALLIBLE_DESTRUCTURING_MATCH,
266+
matches::MANUAL_UNWRAP_OR,
267267
matches::MATCH_AS_REF,
268268
matches::MATCH_BOOL,
269269
matches::MATCH_LIKE_MATCHES_MACRO,

clippy_lints/src/lib.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,6 @@ mod manual_map;
283283
mod manual_non_exhaustive;
284284
mod manual_ok_or;
285285
mod manual_strip;
286-
mod manual_unwrap_or;
287286
mod map_clone;
288287
mod map_err_ignore;
289288
mod map_unit_fn;
@@ -834,7 +833,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
834833
store.register_late_pass(|| Box::new(repeat_once::RepeatOnce));
835834
store.register_late_pass(|| Box::new(unwrap_in_result::UnwrapInResult));
836835
store.register_late_pass(|| Box::new(self_assignment::SelfAssignment));
837-
store.register_late_pass(|| Box::new(manual_unwrap_or::ManualUnwrapOr));
838836
store.register_late_pass(|| Box::new(manual_ok_or::ManualOkOr));
839837
store.register_late_pass(|| Box::new(float_equality_without_abs::FloatEqualityWithoutAbs));
840838
store.register_late_pass(|| Box::new(semicolon_if_nothing_returned::SemicolonIfNothingReturned));

clippy_lints/src/manual_unwrap_or.rs

Lines changed: 0 additions & 123 deletions
This file was deleted.
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
use clippy_utils::consts::constant_simple;
2+
use clippy_utils::diagnostics::span_lint_and_sugg;
3+
use clippy_utils::source::{indent_of, reindent_multiline, snippet_opt};
4+
use clippy_utils::ty::is_type_diagnostic_item;
5+
use clippy_utils::usage::contains_return_break_continue_macro;
6+
use clippy_utils::{is_lang_ctor, path_to_local_id, sugg};
7+
use if_chain::if_chain;
8+
use rustc_errors::Applicability;
9+
use rustc_hir::LangItem::{OptionNone, OptionSome, ResultErr, ResultOk};
10+
use rustc_hir::{Arm, Expr, PatKind};
11+
use rustc_lint::LateContext;
12+
use rustc_span::sym;
13+
14+
use super::MANUAL_UNWRAP_OR;
15+
16+
pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>, scrutinee: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
17+
let ty = cx.typeck_results().expr_ty(scrutinee);
18+
if_chain! {
19+
if let Some(ty_name) = if is_type_diagnostic_item(cx, ty, sym::Option) {
20+
Some("Option")
21+
} else if is_type_diagnostic_item(cx, ty, sym::Result) {
22+
Some("Result")
23+
} else {
24+
None
25+
};
26+
if let Some(or_arm) = applicable_or_arm(cx, arms);
27+
if let Some(or_body_snippet) = snippet_opt(cx, or_arm.body.span);
28+
if let Some(indent) = indent_of(cx, expr.span);
29+
if constant_simple(cx, cx.typeck_results(), or_arm.body).is_some();
30+
then {
31+
let reindented_or_body =
32+
reindent_multiline(or_body_snippet.into(), true, Some(indent));
33+
34+
let suggestion = if scrutinee.span.from_expansion() {
35+
// we don't want parentheses around macro, e.g. `(some_macro!()).unwrap_or(0)`
36+
sugg::Sugg::hir_with_macro_callsite(cx, scrutinee, "..")
37+
}
38+
else {
39+
sugg::Sugg::hir(cx, scrutinee, "..").maybe_par()
40+
};
41+
42+
span_lint_and_sugg(
43+
cx,
44+
MANUAL_UNWRAP_OR, expr.span,
45+
&format!("this pattern reimplements `{}::unwrap_or`", ty_name),
46+
"replace with",
47+
format!(
48+
"{}.unwrap_or({})",
49+
suggestion,
50+
reindented_or_body,
51+
),
52+
Applicability::MachineApplicable,
53+
);
54+
}
55+
}
56+
}
57+
58+
fn applicable_or_arm<'a>(cx: &LateContext<'_>, arms: &'a [Arm<'a>]) -> Option<&'a Arm<'a>> {
59+
if_chain! {
60+
if arms.len() == 2;
61+
if arms.iter().all(|arm| arm.guard.is_none());
62+
if let Some((idx, or_arm)) = arms.iter().enumerate().find(|(_, arm)| {
63+
match arm.pat.kind {
64+
PatKind::Path(ref qpath) => is_lang_ctor(cx, qpath, OptionNone),
65+
PatKind::TupleStruct(ref qpath, [pat], _) =>
66+
matches!(pat.kind, PatKind::Wild) && is_lang_ctor(cx, qpath, ResultErr),
67+
_ => false,
68+
}
69+
});
70+
let unwrap_arm = &arms[1 - idx];
71+
if let PatKind::TupleStruct(ref qpath, [unwrap_pat], _) = unwrap_arm.pat.kind;
72+
if is_lang_ctor(cx, qpath, OptionSome) || is_lang_ctor(cx, qpath, ResultOk);
73+
if let PatKind::Binding(_, binding_hir_id, ..) = unwrap_pat.kind;
74+
if path_to_local_id(unwrap_arm.body, binding_hir_id);
75+
if cx.typeck_results().expr_adjustments(unwrap_arm.body).is_empty();
76+
if !contains_return_break_continue_macro(or_arm.body);
77+
then {
78+
Some(or_arm)
79+
} else {
80+
None
81+
}
82+
}
83+
}

clippy_lints/src/matches/mod.rs

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use clippy_utils::source::{snippet_opt, span_starts_with, walk_span_to_context};
2-
use clippy_utils::{higher, meets_msrv, msrvs};
2+
use clippy_utils::{higher, in_constant, meets_msrv, msrvs};
33
use rustc_hir::{Arm, Expr, ExprKind, Local, MatchSource, Pat};
44
use rustc_lexer::{tokenize, TokenKind};
55
use rustc_lint::{LateContext, LateLintPass, LintContext};
@@ -10,6 +10,7 @@ use rustc_span::{Span, SpanData, SyntaxContext};
1010

1111
mod collapsible_match;
1212
mod infallible_destructuring_match;
13+
mod manual_unwrap_or;
1314
mod match_as_ref;
1415
mod match_bool;
1516
mod match_like_matches;
@@ -650,6 +651,33 @@ declare_clippy_lint! {
650651
"Nested `match` or `if let` expressions where the patterns may be \"collapsed\" together."
651652
}
652653

654+
declare_clippy_lint! {
655+
/// ### What it does
656+
/// Finds patterns that reimplement `Option::unwrap_or` or `Result::unwrap_or`.
657+
///
658+
/// ### Why is this bad?
659+
/// Concise code helps focusing on behavior instead of boilerplate.
660+
///
661+
/// ### Example
662+
/// ```rust
663+
/// let foo: Option<i32> = None;
664+
/// match foo {
665+
/// Some(v) => v,
666+
/// None => 1,
667+
/// };
668+
/// ```
669+
///
670+
/// Use instead:
671+
/// ```rust
672+
/// let foo: Option<i32> = None;
673+
/// foo.unwrap_or(1);
674+
/// ```
675+
#[clippy::version = "1.49.0"]
676+
pub MANUAL_UNWRAP_OR,
677+
complexity,
678+
"finds patterns that can be encoded more concisely with `Option::unwrap_or` or `Result::unwrap_or`"
679+
}
680+
653681
#[derive(Default)]
654682
pub struct Matches {
655683
msrv: Option<RustcVersion>,
@@ -685,6 +713,7 @@ impl_lint_pass!(Matches => [
685713
MATCH_SAME_ARMS,
686714
NEEDLESS_MATCH,
687715
COLLAPSIBLE_MATCH,
716+
MANUAL_UNWRAP_OR,
688717
]);
689718

690719
impl<'tcx> LateLintPass<'tcx> for Matches {
@@ -722,6 +751,10 @@ impl<'tcx> LateLintPass<'tcx> for Matches {
722751
match_as_ref::check(cx, ex, arms, expr);
723752
needless_match::check_match(cx, ex, arms, expr);
724753

754+
if !in_constant(cx, expr.hir_id) {
755+
manual_unwrap_or::check(cx, expr, ex, arms);
756+
}
757+
725758
if self.infallible_destructuring_match_linted {
726759
self.infallible_destructuring_match_linted = false;
727760
} else {

0 commit comments

Comments
 (0)