Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit 4e83a38

Browse files
committed
Auto merge of rust-lang#6123 - montrivo:less_concise_than, r=ebroto
add lint manual_unwrap_or Implements partially rust-lang#5923. changelog: add lint manual_unwrap_or
2 parents 81890c5 + 690a6a6 commit 4e83a38

12 files changed

+405
-76
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1796,6 +1796,7 @@ Released 2018-09-13
17961796
[`manual_saturating_arithmetic`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_saturating_arithmetic
17971797
[`manual_strip`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_strip
17981798
[`manual_swap`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_swap
1799+
[`manual_unwrap_or`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_unwrap_or
17991800
[`many_single_char_names`]: https://rust-lang.github.io/rust-clippy/master/index.html#many_single_char_names
18001801
[`map_clone`]: https://rust-lang.github.io/rust-clippy/master/index.html#map_clone
18011802
[`map_entry`]: https://rust-lang.github.io/rust-clippy/master/index.html#map_entry

clippy_lints/src/lib.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,7 @@ mod main_recursion;
234234
mod manual_async_fn;
235235
mod manual_non_exhaustive;
236236
mod manual_strip;
237+
mod manual_unwrap_or;
237238
mod map_clone;
238239
mod map_err_ignore;
239240
mod map_identity;
@@ -640,6 +641,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
640641
&manual_async_fn::MANUAL_ASYNC_FN,
641642
&manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE,
642643
&manual_strip::MANUAL_STRIP,
644+
&manual_unwrap_or::MANUAL_UNWRAP_OR,
643645
&map_clone::MAP_CLONE,
644646
&map_err_ignore::MAP_ERR_IGNORE,
645647
&map_identity::MAP_IDENTITY,
@@ -1126,6 +1128,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
11261128
store.register_late_pass(|| box repeat_once::RepeatOnce);
11271129
store.register_late_pass(|| box unwrap_in_result::UnwrapInResult);
11281130
store.register_late_pass(|| box self_assignment::SelfAssignment);
1131+
store.register_late_pass(|| box manual_unwrap_or::ManualUnwrapOr);
11291132
store.register_late_pass(|| box float_equality_without_abs::FloatEqualityWithoutAbs);
11301133
store.register_late_pass(|| box async_yields_async::AsyncYieldsAsync);
11311134
store.register_late_pass(|| box manual_strip::ManualStrip);
@@ -1367,6 +1370,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
13671370
LintId::of(&manual_async_fn::MANUAL_ASYNC_FN),
13681371
LintId::of(&manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE),
13691372
LintId::of(&manual_strip::MANUAL_STRIP),
1373+
LintId::of(&manual_unwrap_or::MANUAL_UNWRAP_OR),
13701374
LintId::of(&map_clone::MAP_CLONE),
13711375
LintId::of(&map_identity::MAP_IDENTITY),
13721376
LintId::of(&map_unit_fn::OPTION_MAP_UNIT_FN),
@@ -1662,6 +1666,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
16621666
LintId::of(&loops::MUT_RANGE_BOUND),
16631667
LintId::of(&loops::WHILE_LET_LOOP),
16641668
LintId::of(&manual_strip::MANUAL_STRIP),
1669+
LintId::of(&manual_unwrap_or::MANUAL_UNWRAP_OR),
16651670
LintId::of(&map_identity::MAP_IDENTITY),
16661671
LintId::of(&map_unit_fn::OPTION_MAP_UNIT_FN),
16671672
LintId::of(&map_unit_fn::RESULT_MAP_UNIT_FN),

clippy_lints/src/manual_unwrap_or.rs

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
use crate::consts::constant_simple;
2+
use crate::utils;
3+
use if_chain::if_chain;
4+
use rustc_errors::Applicability;
5+
use rustc_hir::{def, Arm, Expr, ExprKind, PatKind, QPath};
6+
use rustc_lint::LintContext;
7+
use rustc_lint::{LateContext, LateLintPass};
8+
use rustc_middle::lint::in_external_macro;
9+
use rustc_session::{declare_lint_pass, declare_tool_lint};
10+
11+
declare_clippy_lint! {
12+
/// **What it does:**
13+
/// Finds patterns that reimplement `Option::unwrap_or`.
14+
///
15+
/// **Why is this bad?**
16+
/// Concise code helps focusing on behavior instead of boilerplate.
17+
///
18+
/// **Known problems:** None.
19+
///
20+
/// **Example:**
21+
/// ```rust
22+
/// let foo: Option<i32> = None;
23+
/// match foo {
24+
/// Some(v) => v,
25+
/// None => 1,
26+
/// };
27+
/// ```
28+
///
29+
/// Use instead:
30+
/// ```rust
31+
/// let foo: Option<i32> = None;
32+
/// foo.unwrap_or(1);
33+
/// ```
34+
pub MANUAL_UNWRAP_OR,
35+
complexity,
36+
"finds patterns that can be encoded more concisely with `Option::unwrap_or`"
37+
}
38+
39+
declare_lint_pass!(ManualUnwrapOr => [MANUAL_UNWRAP_OR]);
40+
41+
impl LateLintPass<'_> for ManualUnwrapOr {
42+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
43+
if in_external_macro(cx.sess(), expr.span) {
44+
return;
45+
}
46+
lint_option_unwrap_or_case(cx, expr);
47+
}
48+
}
49+
50+
fn lint_option_unwrap_or_case<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
51+
fn applicable_none_arm<'a>(arms: &'a [Arm<'a>]) -> Option<&'a Arm<'a>> {
52+
if_chain! {
53+
if arms.len() == 2;
54+
if arms.iter().all(|arm| arm.guard.is_none());
55+
if let Some((idx, none_arm)) = arms.iter().enumerate().find(|(_, arm)|
56+
if let PatKind::Path(ref qpath) = arm.pat.kind {
57+
utils::match_qpath(qpath, &utils::paths::OPTION_NONE)
58+
} else {
59+
false
60+
}
61+
);
62+
let some_arm = &arms[1 - idx];
63+
if let PatKind::TupleStruct(ref some_qpath, &[some_binding], _) = some_arm.pat.kind;
64+
if utils::match_qpath(some_qpath, &utils::paths::OPTION_SOME);
65+
if let PatKind::Binding(_, binding_hir_id, ..) = some_binding.kind;
66+
if let ExprKind::Path(QPath::Resolved(_, body_path)) = some_arm.body.kind;
67+
if let def::Res::Local(body_path_hir_id) = body_path.res;
68+
if body_path_hir_id == binding_hir_id;
69+
if !utils::usage::contains_return_break_continue_macro(none_arm.body);
70+
then {
71+
Some(none_arm)
72+
} else {
73+
None
74+
}
75+
}
76+
}
77+
78+
if_chain! {
79+
if let ExprKind::Match(scrutinee, match_arms, _) = expr.kind;
80+
let ty = cx.typeck_results().expr_ty(scrutinee);
81+
if utils::is_type_diagnostic_item(cx, ty, sym!(option_type));
82+
if let Some(none_arm) = applicable_none_arm(match_arms);
83+
if let Some(scrutinee_snippet) = utils::snippet_opt(cx, scrutinee.span);
84+
if let Some(none_body_snippet) = utils::snippet_opt(cx, none_arm.body.span);
85+
if let Some(indent) = utils::indent_of(cx, expr.span);
86+
if constant_simple(cx, cx.typeck_results(), none_arm.body).is_some();
87+
then {
88+
let reindented_none_body =
89+
utils::reindent_multiline(none_body_snippet.into(), true, Some(indent));
90+
utils::span_lint_and_sugg(
91+
cx,
92+
MANUAL_UNWRAP_OR, expr.span,
93+
"this pattern reimplements `Option::unwrap_or`",
94+
"replace with",
95+
format!(
96+
"{}.unwrap_or({})",
97+
scrutinee_snippet,
98+
reindented_none_body,
99+
),
100+
Applicability::MachineApplicable,
101+
);
102+
}
103+
}
104+
}

clippy_lints/src/option_if_let_else.rs

Lines changed: 2 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,8 @@ use crate::utils::{is_type_diagnostic_item, paths, span_lint_and_sugg};
55
use if_chain::if_chain;
66

77
use rustc_errors::Applicability;
8-
use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
98
use rustc_hir::{Arm, BindingAnnotation, Block, Expr, ExprKind, MatchSource, Mutability, PatKind, UnOp};
109
use rustc_lint::{LateContext, LateLintPass};
11-
use rustc_middle::hir::map::Map;
1210
use rustc_session::{declare_lint_pass, declare_tool_lint};
1311

1412
declare_clippy_lint! {
@@ -84,53 +82,6 @@ struct OptionIfLetElseOccurence {
8482
wrap_braces: bool,
8583
}
8684

87-
struct ReturnBreakContinueMacroVisitor {
88-
seen_return_break_continue: bool,
89-
}
90-
91-
impl ReturnBreakContinueMacroVisitor {
92-
fn new() -> ReturnBreakContinueMacroVisitor {
93-
ReturnBreakContinueMacroVisitor {
94-
seen_return_break_continue: false,
95-
}
96-
}
97-
}
98-
99-
impl<'tcx> Visitor<'tcx> for ReturnBreakContinueMacroVisitor {
100-
type Map = Map<'tcx>;
101-
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
102-
NestedVisitorMap::None
103-
}
104-
105-
fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
106-
if self.seen_return_break_continue {
107-
// No need to look farther if we've already seen one of them
108-
return;
109-
}
110-
match &ex.kind {
111-
ExprKind::Ret(..) | ExprKind::Break(..) | ExprKind::Continue(..) => {
112-
self.seen_return_break_continue = true;
113-
},
114-
// Something special could be done here to handle while or for loop
115-
// desugaring, as this will detect a break if there's a while loop
116-
// or a for loop inside the expression.
117-
_ => {
118-
if utils::in_macro(ex.span) {
119-
self.seen_return_break_continue = true;
120-
} else {
121-
rustc_hir::intravisit::walk_expr(self, ex);
122-
}
123-
},
124-
}
125-
}
126-
}
127-
128-
fn contains_return_break_continue_macro(expression: &Expr<'_>) -> bool {
129-
let mut recursive_visitor = ReturnBreakContinueMacroVisitor::new();
130-
recursive_visitor.visit_expr(expression);
131-
recursive_visitor.seen_return_break_continue
132-
}
133-
13485
/// Extracts the body of a given arm. If the arm contains only an expression,
13586
/// then it returns the expression. Otherwise, it returns the entire block
13687
fn extract_body_from_arm<'a>(arm: &'a Arm<'a>) -> Option<&'a Expr<'a>> {
@@ -208,8 +159,8 @@ fn detect_option_if_let_else<'tcx>(
208159
if let PatKind::TupleStruct(struct_qpath, &[inner_pat], _) = &arms[0].pat.kind;
209160
if utils::match_qpath(struct_qpath, &paths::OPTION_SOME);
210161
if let PatKind::Binding(bind_annotation, _, id, _) = &inner_pat.kind;
211-
if !contains_return_break_continue_macro(arms[0].body);
212-
if !contains_return_break_continue_macro(arms[1].body);
162+
if !utils::usage::contains_return_break_continue_macro(arms[0].body);
163+
if !utils::usage::contains_return_break_continue_macro(arms[1].body);
213164
then {
214165
let capture_mut = if bind_annotation == &BindingAnnotation::Mutable { "mut " } else { "" };
215166
let some_body = extract_body_from_arm(&arms[0])?;

clippy_lints/src/utils/eager_or_lazy.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ fn identify_some_pure_patterns(expr: &Expr<'_>) -> bool {
8282
/// Identify some potentially computationally expensive patterns.
8383
/// This function is named so to stress that its implementation is non-exhaustive.
8484
/// It returns FNs and FPs.
85-
fn identify_some_potentially_expensive_patterns<'a, 'tcx>(cx: &'a LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
85+
fn identify_some_potentially_expensive_patterns<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
8686
// Searches an expression for method calls or function calls that aren't ctors
8787
struct FunCallFinder<'a, 'tcx> {
8888
cx: &'a LateContext<'tcx>,

clippy_lints/src/utils/usage.rs

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1+
use crate::utils;
12
use crate::utils::match_var;
23
use rustc_data_structures::fx::FxHashSet;
34
use rustc_hir as hir;
45
use rustc_hir::def::Res;
56
use rustc_hir::intravisit;
67
use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
7-
use rustc_hir::{Expr, HirId, Path};
8+
use rustc_hir::{Expr, ExprKind, HirId, Path};
89
use rustc_infer::infer::TyCtxtInferExt;
910
use rustc_lint::LateContext;
1011
use rustc_middle::hir::map::Map;
@@ -174,3 +175,50 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for BindingUsageFinder<'a, 'tcx> {
174175
intravisit::NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
175176
}
176177
}
178+
179+
struct ReturnBreakContinueMacroVisitor {
180+
seen_return_break_continue: bool,
181+
}
182+
183+
impl ReturnBreakContinueMacroVisitor {
184+
fn new() -> ReturnBreakContinueMacroVisitor {
185+
ReturnBreakContinueMacroVisitor {
186+
seen_return_break_continue: false,
187+
}
188+
}
189+
}
190+
191+
impl<'tcx> Visitor<'tcx> for ReturnBreakContinueMacroVisitor {
192+
type Map = Map<'tcx>;
193+
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
194+
NestedVisitorMap::None
195+
}
196+
197+
fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
198+
if self.seen_return_break_continue {
199+
// No need to look farther if we've already seen one of them
200+
return;
201+
}
202+
match &ex.kind {
203+
ExprKind::Ret(..) | ExprKind::Break(..) | ExprKind::Continue(..) => {
204+
self.seen_return_break_continue = true;
205+
},
206+
// Something special could be done here to handle while or for loop
207+
// desugaring, as this will detect a break if there's a while loop
208+
// or a for loop inside the expression.
209+
_ => {
210+
if utils::in_macro(ex.span) {
211+
self.seen_return_break_continue = true;
212+
} else {
213+
rustc_hir::intravisit::walk_expr(self, ex);
214+
}
215+
},
216+
}
217+
}
218+
}
219+
220+
pub fn contains_return_break_continue_macro(expression: &Expr<'_>) -> bool {
221+
let mut recursive_visitor = ReturnBreakContinueMacroVisitor::new();
222+
recursive_visitor.visit_expr(expression);
223+
recursive_visitor.seen_return_break_continue
224+
}

src/lintlist/mod.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1180,6 +1180,13 @@ vec![
11801180
deprecation: None,
11811181
module: "swap",
11821182
},
1183+
Lint {
1184+
name: "manual_unwrap_or",
1185+
group: "complexity",
1186+
desc: "finds patterns that can be encoded more concisely with `Option::unwrap_or`",
1187+
deprecation: None,
1188+
module: "manual_unwrap_or",
1189+
},
11831190
Lint {
11841191
name: "many_single_char_names",
11851192
group: "style",

tests/ui/manual_unwrap_or.fixed

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// run-rustfix
2+
#![allow(dead_code)]
3+
4+
fn unwrap_or() {
5+
// int case
6+
Some(1).unwrap_or(42);
7+
8+
// int case reversed
9+
Some(1).unwrap_or(42);
10+
11+
// richer none expr
12+
Some(1).unwrap_or(1 + 42);
13+
14+
// multiline case
15+
#[rustfmt::skip]
16+
Some(1).unwrap_or({
17+
42 + 42
18+
+ 42 + 42 + 42
19+
+ 42 + 42 + 42
20+
});
21+
22+
// string case
23+
Some("Bob").unwrap_or("Alice");
24+
25+
// don't lint
26+
match Some(1) {
27+
Some(i) => i + 2,
28+
None => 42,
29+
};
30+
match Some(1) {
31+
Some(i) => i,
32+
None => return,
33+
};
34+
for j in 0..4 {
35+
match Some(j) {
36+
Some(i) => i,
37+
None => continue,
38+
};
39+
match Some(j) {
40+
Some(i) => i,
41+
None => break,
42+
};
43+
}
44+
45+
// cases where the none arm isn't a constant expression
46+
// are not linted due to potential ownership issues
47+
48+
// ownership issue example, don't lint
49+
struct NonCopyable;
50+
let mut option: Option<NonCopyable> = None;
51+
match option {
52+
Some(x) => x,
53+
None => {
54+
option = Some(NonCopyable);
55+
// some more code ...
56+
option.unwrap()
57+
},
58+
};
59+
60+
// ownership issue example, don't lint
61+
let option: Option<&str> = None;
62+
match option {
63+
Some(s) => s,
64+
None => &format!("{} {}!", "hello", "world"),
65+
};
66+
}
67+
68+
fn main() {}

0 commit comments

Comments
 (0)