Skip to content

Commit 07b2da8

Browse files
committed
add lint less_concise_than_option_unwrap_or
1 parent 0b77c35 commit 07b2da8

File tree

12 files changed

+345
-76
lines changed

12 files changed

+345
-76
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1781,6 +1781,7 @@ Released 2018-09-13
17811781
[`large_stack_arrays`]: https://rust-lang.github.io/rust-clippy/master/index.html#large_stack_arrays
17821782
[`len_without_is_empty`]: https://rust-lang.github.io/rust-clippy/master/index.html#len_without_is_empty
17831783
[`len_zero`]: https://rust-lang.github.io/rust-clippy/master/index.html#len_zero
1784+
[`less_concise_than_option_unwrap_or`]: https://rust-lang.github.io/rust-clippy/master/index.html#less_concise_than_option_unwrap_or
17841785
[`let_and_return`]: https://rust-lang.github.io/rust-clippy/master/index.html#let_and_return
17851786
[`let_underscore_lock`]: https://rust-lang.github.io/rust-clippy/master/index.html#let_underscore_lock
17861787
[`let_underscore_must_use`]: https://rust-lang.github.io/rust-clippy/master/index.html#let_underscore_must_use

clippy_lints/src/less_concise_than.rs

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

clippy_lints/src/lib.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,7 @@ mod large_const_arrays;
224224
mod large_enum_variant;
225225
mod large_stack_arrays;
226226
mod len_zero;
227+
mod less_concise_than;
227228
mod let_if_seq;
228229
mod let_underscore;
229230
mod lifetimes;
@@ -609,6 +610,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
609610
&large_stack_arrays::LARGE_STACK_ARRAYS,
610611
&len_zero::LEN_WITHOUT_IS_EMPTY,
611612
&len_zero::LEN_ZERO,
613+
&less_concise_than::LESS_CONCISE_THAN_OPTION_UNWRAP_OR,
612614
&let_if_seq::USELESS_LET_IF_SEQ,
613615
&let_underscore::LET_UNDERSCORE_LOCK,
614616
&let_underscore::LET_UNDERSCORE_MUST_USE,
@@ -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 less_concise_than::LessConciseThan);
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);
@@ -1210,6 +1213,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
12101213
LintId::of(&infinite_iter::MAYBE_INFINITE_ITER),
12111214
LintId::of(&items_after_statements::ITEMS_AFTER_STATEMENTS),
12121215
LintId::of(&large_stack_arrays::LARGE_STACK_ARRAYS),
1216+
LintId::of(&less_concise_than::LESS_CONCISE_THAN_OPTION_UNWRAP_OR),
12131217
LintId::of(&literal_representation::LARGE_DIGIT_GROUPS),
12141218
LintId::of(&literal_representation::UNREADABLE_LITERAL),
12151219
LintId::of(&loops::EXPLICIT_INTO_ITER_LOOP),

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
@@ -1075,6 +1075,13 @@ vec![
10751075
deprecation: None,
10761076
module: "len_zero",
10771077
},
1078+
Lint {
1079+
name: "less_concise_than_option_unwrap_or",
1080+
group: "pedantic",
1081+
desc: "finds patterns that can be encoded more concisely with `Option::unwrap_or`",
1082+
deprecation: None,
1083+
module: "less_concise_than",
1084+
},
10781085
Lint {
10791086
name: "let_and_return",
10801087
group: "style",

tests/ui/less_concise_than.fixed

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// run-rustfix
2+
#![warn(clippy::less_concise_than_option_unwrap_or)]
3+
#![allow(dead_code)]
4+
5+
fn unwrap_or() {
6+
// int case
7+
Some(1).unwrap_or(42);
8+
9+
// richer none expr
10+
Some(1).unwrap_or_else(|| 1 + 42);
11+
12+
// multiline case
13+
Some(1).unwrap_or_else(|| {
14+
let a = 1 + 42;
15+
let b = a + 42;
16+
b + 42
17+
});
18+
19+
// string case
20+
Some("Bob").unwrap_or("Alice");
21+
22+
// don't lint
23+
match Some(1) {
24+
Some(i) => i + 2,
25+
None => 42,
26+
};
27+
match Some(1) {
28+
Some(i) => i,
29+
None => return,
30+
};
31+
for j in 0..4 {
32+
match Some(j) {
33+
Some(i) => i,
34+
None => continue,
35+
};
36+
match Some(j) {
37+
Some(i) => i,
38+
None => break,
39+
};
40+
}
41+
}
42+
43+
fn main() {}

0 commit comments

Comments
 (0)