Skip to content

Commit 2fc340b

Browse files
committed
Lint for if let Some(x) = ... instead of Option::map_or
1 parent 52cc5fc commit 2fc340b

File tree

7 files changed

+381
-0
lines changed

7 files changed

+381
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1577,6 +1577,7 @@ Released 2018-09-13
15771577
[`op_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#op_ref
15781578
[`option_as_ref_deref`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_as_ref_deref
15791579
[`option_env_unwrap`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_env_unwrap
1580+
[`option_if_let_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_if_let_else
15801581
[`option_map_or_none`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_map_or_none
15811582
[`option_map_unit_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_map_unit_fn
15821583
[`option_option`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_option

clippy_lints/src/lib.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,7 @@ mod non_copy_const;
264264
mod non_expressive_names;
265265
mod open_options;
266266
mod option_env_unwrap;
267+
mod option_if_let_else;
267268
mod overflow_check_conditional;
268269
mod panic_unimplemented;
269270
mod partialeq_ne_impl;
@@ -733,6 +734,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
733734
&non_expressive_names::SIMILAR_NAMES,
734735
&open_options::NONSENSICAL_OPEN_OPTIONS,
735736
&option_env_unwrap::OPTION_ENV_UNWRAP,
737+
&option_if_let_else::OPTION_IF_LET_ELSE,
736738
&overflow_check_conditional::OVERFLOW_CHECK_CONDITIONAL,
737739
&panic_unimplemented::PANIC,
738740
&panic_unimplemented::PANIC_PARAMS,
@@ -1049,6 +1051,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
10491051
store.register_late_pass(|| box redundant_pub_crate::RedundantPubCrate::default());
10501052
store.register_late_pass(|| box unnamed_address::UnnamedAddress);
10511053
store.register_late_pass(|| box dereference::Dereferencing);
1054+
store.register_late_pass(|| box option_if_let_else::OptionIfLetElse);
10521055
store.register_late_pass(|| box future_not_send::FutureNotSend);
10531056
store.register_late_pass(|| box utils::internal_lints::CollapsibleCalls);
10541057
store.register_late_pass(|| box if_let_mutex::IfLetMutex);
@@ -1364,6 +1367,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
13641367
LintId::of(&non_expressive_names::MANY_SINGLE_CHAR_NAMES),
13651368
LintId::of(&open_options::NONSENSICAL_OPEN_OPTIONS),
13661369
LintId::of(&option_env_unwrap::OPTION_ENV_UNWRAP),
1370+
LintId::of(&option_if_let_else::OPTION_IF_LET_ELSE),
13671371
LintId::of(&overflow_check_conditional::OVERFLOW_CHECK_CONDITIONAL),
13681372
LintId::of(&panic_unimplemented::PANIC_PARAMS),
13691373
LintId::of(&partialeq_ne_impl::PARTIALEQ_NE_IMPL),
@@ -1512,6 +1516,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
15121516
LintId::of(&new_without_default::NEW_WITHOUT_DEFAULT),
15131517
LintId::of(&non_expressive_names::JUST_UNDERSCORES_AND_DIGITS),
15141518
LintId::of(&non_expressive_names::MANY_SINGLE_CHAR_NAMES),
1519+
LintId::of(&option_if_let_else::OPTION_IF_LET_ELSE),
15151520
LintId::of(&panic_unimplemented::PANIC_PARAMS),
15161521
LintId::of(&ptr::CMP_NULL),
15171522
LintId::of(&ptr::PTR_ARG),
Lines changed: 202 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
use crate::utils::sugg::Sugg;
2+
use crate::utils::{match_type, paths, span_lint_and_sugg};
3+
use if_chain::if_chain;
4+
5+
use rustc_errors::Applicability;
6+
use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
7+
use rustc_hir::*;
8+
use rustc_lint::{LateContext, LateLintPass};
9+
use rustc_middle::hir::map::Map;
10+
use rustc_session::{declare_lint_pass, declare_tool_lint};
11+
12+
use std::marker::PhantomData;
13+
14+
declare_clippy_lint! {
15+
/// **What it does:**
16+
/// Lints usage of `if let Some(v) = ... { y } else { x }` which is more
17+
/// idiomatically done with `Option::map_or` (if the else bit is a simple
18+
/// expression) or `Option::map_or_else` (if the else bit is a longer
19+
/// block).
20+
///
21+
/// **Why is this bad?**
22+
/// Using the dedicated functions of the Option type is clearer and
23+
/// more concise than an if let expression.
24+
///
25+
/// **Known problems:**
26+
/// This lint uses whether the block is just an expression or if it has
27+
/// more statements to decide whether to use `Option::map_or` or
28+
/// `Option::map_or_else`. If you have a single expression which calls
29+
/// an expensive function, then it would be more efficient to use
30+
/// `Option::map_or_else`, but this lint would suggest `Option::map_or`.
31+
///
32+
/// Also, this lint uses a deliberately conservative metric for checking
33+
/// if the inside of either body contains breaks or continues which will
34+
/// cause it to not suggest a fix if either block contains a loop with
35+
/// continues or breaks contained within the loop.
36+
///
37+
/// **Example:**
38+
///
39+
/// ```rust
40+
/// # let optional: Option<u32> = Some(0);
41+
/// let _ = if let Some(foo) = optional {
42+
/// foo
43+
/// } else {
44+
/// 5
45+
/// };
46+
/// let _ = if let Some(foo) = optional {
47+
/// foo
48+
/// } else {
49+
/// let y = do_complicated_function();
50+
/// y*y
51+
/// };
52+
/// ```
53+
///
54+
/// should be
55+
///
56+
/// ```rust
57+
/// # let optional: Option<u32> = Some(0);
58+
/// let _ = optional.map_or(5, |foo| foo);
59+
/// let _ = optional.map_or_else(||{
60+
/// let y = do_complicated_function;
61+
/// y*y
62+
/// }, |foo| foo);
63+
/// ```
64+
pub OPTION_IF_LET_ELSE,
65+
style,
66+
"reimplementation of Option::map_or"
67+
}
68+
69+
declare_lint_pass!(OptionIfLetElse => [OPTION_IF_LET_ELSE]);
70+
71+
/// Returns true iff the given expression is the result of calling Result::ok
72+
fn is_result_ok(cx: &LateContext<'_, '_>, expr: &'_ Expr<'_>) -> bool {
73+
if_chain! {
74+
if let ExprKind::MethodCall(ref path, _, &[ref receiver]) = &expr.kind;
75+
if path.ident.name.to_ident_string() == "ok";
76+
if match_type(cx, &cx.tables.expr_ty(&receiver), &paths::RESULT);
77+
then {
78+
true
79+
} else {
80+
false
81+
}
82+
}
83+
}
84+
85+
/// A struct containing information about occurences of the
86+
/// `if let Some(..) = .. else` construct that this lint detects.
87+
struct OptionIfLetElseOccurence {
88+
option: String,
89+
method_sugg: String,
90+
some_expr: String,
91+
none_expr: String,
92+
}
93+
94+
struct ReturnBreakContinueVisitor<'tcx> {
95+
seen_return_break_continue: bool,
96+
phantom_data: PhantomData<&'tcx bool>,
97+
}
98+
impl<'tcx> ReturnBreakContinueVisitor<'tcx> {
99+
fn new() -> ReturnBreakContinueVisitor<'tcx> {
100+
ReturnBreakContinueVisitor {
101+
seen_return_break_continue: false,
102+
phantom_data: PhantomData,
103+
}
104+
}
105+
}
106+
impl<'tcx> Visitor<'tcx> for ReturnBreakContinueVisitor<'tcx> {
107+
type Map = Map<'tcx>;
108+
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
109+
NestedVisitorMap::None
110+
}
111+
112+
fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
113+
if self.seen_return_break_continue {
114+
// No need to look farther if we've already seen one of them
115+
return;
116+
}
117+
match &ex.kind {
118+
ExprKind::Ret(..) | ExprKind::Break(..) | ExprKind::Continue(..) => {
119+
self.seen_return_break_continue = true;
120+
},
121+
// Something special could be done here to handle while or for loop
122+
// desugaring, as this will detect a break if there's a while loop
123+
// or a for loop inside the expression.
124+
_ => {
125+
rustc_hir::intravisit::walk_expr(self, ex);
126+
},
127+
}
128+
}
129+
}
130+
131+
fn contains_return_break_continue<'tcx>(expression: &'tcx Expr<'tcx>) -> bool {
132+
let mut recursive_visitor: ReturnBreakContinueVisitor<'tcx> = ReturnBreakContinueVisitor::new();
133+
recursive_visitor.visit_expr(expression);
134+
recursive_visitor.seen_return_break_continue
135+
}
136+
137+
/// If this expression is the option if let/else construct we're detecting, then
138+
/// this function returns an OptionIfLetElseOccurence struct with details if
139+
/// this construct is found, or None if this construct is not found.
140+
fn detect_option_if_let_else<'a>(cx: &LateContext<'_, 'a>, expr: &'a Expr<'a>) -> Option<OptionIfLetElseOccurence> {
141+
//(String, String, String, String)> {
142+
if_chain! {
143+
if let ExprKind::Match(let_body, arms, MatchSource::IfLetDesugar{contains_else_clause: true}) = &expr.kind;
144+
if arms.len() == 2;
145+
if match_type(cx, &cx.tables.expr_ty(let_body), &paths::OPTION);
146+
if !is_result_ok(cx, let_body); // Don't lint on Result::ok because a different lint does it already
147+
if let PatKind::TupleStruct(_, &[inner_pat], _) = &arms[0].pat.kind;
148+
if let PatKind::Binding(_, _, id, _) = &inner_pat.kind;
149+
if !contains_return_break_continue(arms[0].body);
150+
if !contains_return_break_continue(arms[1].body);
151+
then {
152+
let some_body = if let ExprKind::Block(Block { stmts: statements, expr: Some(expr), .. }, _)
153+
= &arms[0].body.kind {
154+
if let &[] = &statements {
155+
expr
156+
} else {
157+
&arms[0].body
158+
}
159+
} else {
160+
return None;
161+
};
162+
let (none_body, method_sugg) = if let ExprKind::Block(Block { stmts: statements, expr: Some(expr), .. }, _)
163+
= &arms[1].body.kind {
164+
if let &[] = &statements {
165+
(expr, "map_or")
166+
} else {
167+
(&arms[1].body, "map_or_else")
168+
}
169+
} else {
170+
return None;
171+
};
172+
let capture_name = id.name.to_ident_string();
173+
Some(OptionIfLetElseOccurence {
174+
option: format!("{}", Sugg::hir(cx, let_body, "..")),
175+
method_sugg: format!("{}", method_sugg),
176+
some_expr: format!("|{}| {}", capture_name, Sugg::hir(cx, some_body, "..")),
177+
none_expr: format!("{}{}", if method_sugg == "map_or" { "" } else { "|| " }, Sugg::hir(cx, none_body, ".."))
178+
})
179+
} else {
180+
None
181+
}
182+
}
183+
}
184+
185+
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OptionIfLetElse {
186+
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
187+
if let Some(detection) = detect_option_if_let_else(cx, expr) {
188+
span_lint_and_sugg(
189+
cx,
190+
OPTION_IF_LET_ELSE,
191+
expr.span,
192+
format!("use Option::{} instead of an if let/else", detection.method_sugg).as_str(),
193+
"try",
194+
format!(
195+
"{}.{}({}, {})",
196+
detection.option, detection.method_sugg, detection.none_expr, detection.some_expr
197+
),
198+
Applicability::MachineApplicable,
199+
);
200+
}
201+
}
202+
}

src/lintlist/mod.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1620,6 +1620,13 @@ pub static ref ALL_LINTS: Vec<Lint> = vec![
16201620
deprecation: None,
16211621
module: "option_env_unwrap",
16221622
},
1623+
Lint {
1624+
name: "option_if_let_else",
1625+
group: "style",
1626+
desc: "reimplementation of Option::map_or",
1627+
deprecation: None,
1628+
module: "option_if_let_else",
1629+
},
16231630
Lint {
16241631
name: "option_map_or_none",
16251632
group: "style",

tests/ui/option_if_let_else.fixed

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// run-rustfix
2+
#![warn(clippy::option_if_let_else)]
3+
4+
fn bad1(string: Option<&str>) -> (bool, &str) {
5+
string.map_or((false, "hello"), |x| (true, x))
6+
}
7+
8+
fn longer_body(arg: Option<u32>) -> u32 {
9+
arg.map_or(13, |x| {
10+
let y = x * x;
11+
y * y
12+
})
13+
}
14+
15+
fn test_map_or_else(arg: Option<u32>) {
16+
let _ = arg.map_or_else(|| {
17+
let mut y = 1;
18+
y = (y + 2 / y) / 2;
19+
y = (y + 2 / y) / 2;
20+
y
21+
}, |x| x * x * x * x);
22+
}
23+
24+
fn negative_tests(arg: Option<u32>) -> u32 {
25+
let _ = if let Some(13) = arg { "unlucky" } else { "lucky" };
26+
for _ in 0..10 {
27+
let _ = if let Some(x) = arg {
28+
x
29+
} else {
30+
continue;
31+
};
32+
}
33+
let _ = if let Some(x) = arg {
34+
return x;
35+
} else {
36+
5
37+
};
38+
7
39+
}
40+
41+
fn main() {
42+
let optional = Some(5);
43+
let _ = optional.map_or(5, |x| x + 2);
44+
let _ = bad1(None);
45+
let _ = longer_body(None);
46+
test_map_or_else(None);
47+
let _ = negative_tests(None);
48+
}

tests/ui/option_if_let_else.rs

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// run-rustfix
2+
#![warn(clippy::option_if_let_else)]
3+
4+
fn bad1(string: Option<&str>) -> (bool, &str) {
5+
if let Some(x) = string {
6+
(true, x)
7+
} else {
8+
(false, "hello")
9+
}
10+
}
11+
12+
fn longer_body(arg: Option<u32>) -> u32 {
13+
if let Some(x) = arg {
14+
let y = x * x;
15+
y * y
16+
} else {
17+
13
18+
}
19+
}
20+
21+
fn test_map_or_else(arg: Option<u32>) {
22+
let _ = if let Some(x) = arg {
23+
x * x * x * x
24+
} else {
25+
let mut y = 1;
26+
y = (y + 2 / y) / 2;
27+
y = (y + 2 / y) / 2;
28+
y
29+
};
30+
}
31+
32+
fn negative_tests(arg: Option<u32>) -> u32 {
33+
let _ = if let Some(13) = arg { "unlucky" } else { "lucky" };
34+
for _ in 0..10 {
35+
let _ = if let Some(x) = arg {
36+
x
37+
} else {
38+
continue;
39+
};
40+
}
41+
let _ = if let Some(x) = arg {
42+
return x;
43+
} else {
44+
5
45+
};
46+
7
47+
}
48+
49+
fn main() {
50+
let optional = Some(5);
51+
let _ = if let Some(x) = optional { x + 2 } else { 5 };
52+
let _ = bad1(None);
53+
let _ = longer_body(None);
54+
test_map_or_else(None);
55+
let _ = negative_tests(None);
56+
}

0 commit comments

Comments
 (0)