Skip to content

Commit 781de34

Browse files
committed
Auto merge of #6859 - magurotuna:if_then_some_else_none, r=giraffate
Implement new lint: if_then_some_else_none Resolves #6760 changelog: Added a new lint: `if_then_some_else_none`
2 parents 92b9677 + 11d2af7 commit 781de34

File tree

5 files changed

+285
-0
lines changed

5 files changed

+285
-0
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -2103,6 +2103,7 @@ Released 2018-09-13
21032103
[`if_let_some_result`]: https://rust-lang.github.io/rust-clippy/master/index.html#if_let_some_result
21042104
[`if_not_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#if_not_else
21052105
[`if_same_then_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#if_same_then_else
2106+
[`if_then_some_else_none`]: https://rust-lang.github.io/rust-clippy/master/index.html#if_then_some_else_none
21062107
[`ifs_same_cond`]: https://rust-lang.github.io/rust-clippy/master/index.html#ifs_same_cond
21072108
[`implicit_clone`]: https://rust-lang.github.io/rust-clippy/master/index.html#implicit_clone
21082109
[`implicit_hasher`]: https://rust-lang.github.io/rust-clippy/master/index.html#implicit_hasher
+115
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
use crate::utils;
2+
use if_chain::if_chain;
3+
use rustc_hir::{Expr, ExprKind};
4+
use rustc_lint::{LateContext, LateLintPass, LintContext};
5+
use rustc_middle::lint::in_external_macro;
6+
use rustc_semver::RustcVersion;
7+
use rustc_session::{declare_tool_lint, impl_lint_pass};
8+
9+
const IF_THEN_SOME_ELSE_NONE_MSRV: RustcVersion = RustcVersion::new(1, 50, 0);
10+
11+
declare_clippy_lint! {
12+
/// **What it does:** Checks for if-else that could be written to `bool::then`.
13+
///
14+
/// **Why is this bad?** Looks a little redundant. Using `bool::then` helps it have less lines of code.
15+
///
16+
/// **Known problems:** None.
17+
///
18+
/// **Example:**
19+
///
20+
/// ```rust
21+
/// # let v = vec![0];
22+
/// let a = if v.is_empty() {
23+
/// println!("true!");
24+
/// Some(42)
25+
/// } else {
26+
/// None
27+
/// };
28+
/// ```
29+
///
30+
/// Could be written:
31+
///
32+
/// ```rust
33+
/// # let v = vec![0];
34+
/// let a = v.is_empty().then(|| {
35+
/// println!("true!");
36+
/// 42
37+
/// });
38+
/// ```
39+
pub IF_THEN_SOME_ELSE_NONE,
40+
restriction,
41+
"Finds if-else that could be written using `bool::then`"
42+
}
43+
44+
pub struct IfThenSomeElseNone {
45+
msrv: Option<RustcVersion>,
46+
}
47+
48+
impl IfThenSomeElseNone {
49+
#[must_use]
50+
pub fn new(msrv: Option<RustcVersion>) -> Self {
51+
Self { msrv }
52+
}
53+
}
54+
55+
impl_lint_pass!(IfThenSomeElseNone => [IF_THEN_SOME_ELSE_NONE]);
56+
57+
impl LateLintPass<'_> for IfThenSomeElseNone {
58+
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'tcx Expr<'_>) {
59+
if !utils::meets_msrv(self.msrv.as_ref(), &IF_THEN_SOME_ELSE_NONE_MSRV) {
60+
return;
61+
}
62+
63+
if in_external_macro(cx.sess(), expr.span) {
64+
return;
65+
}
66+
67+
// We only care about the top-most `if` in the chain
68+
if utils::parent_node_is_if_expr(expr, cx) {
69+
return;
70+
}
71+
72+
if_chain! {
73+
if let ExprKind::If(ref cond, ref then, Some(ref els)) = expr.kind;
74+
if let ExprKind::Block(ref then_block, _) = then.kind;
75+
if let Some(ref then_expr) = then_block.expr;
76+
if let ExprKind::Call(ref then_call, [then_arg]) = then_expr.kind;
77+
if let ExprKind::Path(ref then_call_qpath) = then_call.kind;
78+
if utils::match_qpath(then_call_qpath, &utils::paths::OPTION_SOME);
79+
if let ExprKind::Block(ref els_block, _) = els.kind;
80+
if els_block.stmts.is_empty();
81+
if let Some(ref els_expr) = els_block.expr;
82+
if let ExprKind::Path(ref els_call_qpath) = els_expr.kind;
83+
if utils::match_qpath(els_call_qpath, &utils::paths::OPTION_NONE);
84+
then {
85+
let cond_snip = utils::snippet_with_macro_callsite(cx, cond.span, "[condition]");
86+
let cond_snip = if matches!(cond.kind, ExprKind::Unary(_, _) | ExprKind::Binary(_, _, _)) {
87+
format!("({})", cond_snip)
88+
} else {
89+
cond_snip.into_owned()
90+
};
91+
let arg_snip = utils::snippet_with_macro_callsite(cx, then_arg.span, "");
92+
let closure_body = if then_block.stmts.is_empty() {
93+
arg_snip.into_owned()
94+
} else {
95+
format!("{{ /* snippet */ {} }}", arg_snip)
96+
};
97+
let help = format!(
98+
"consider using `bool::then` like: `{}.then(|| {})`",
99+
cond_snip,
100+
closure_body,
101+
);
102+
utils::span_lint_and_help(
103+
cx,
104+
IF_THEN_SOME_ELSE_NONE,
105+
expr.span,
106+
"this could be simplified with `bool::then`",
107+
None,
108+
&help,
109+
);
110+
}
111+
}
112+
}
113+
114+
extract_msrv_attr!(LateContext);
115+
}

clippy_lints/src/lib.rs

+4
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,7 @@ mod identity_op;
231231
mod if_let_mutex;
232232
mod if_let_some_result;
233233
mod if_not_else;
234+
mod if_then_some_else_none;
234235
mod implicit_return;
235236
mod implicit_saturating_sub;
236237
mod inconsistent_struct_constructor;
@@ -680,6 +681,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
680681
&if_let_mutex::IF_LET_MUTEX,
681682
&if_let_some_result::IF_LET_SOME_RESULT,
682683
&if_not_else::IF_NOT_ELSE,
684+
&if_then_some_else_none::IF_THEN_SOME_ELSE_NONE,
683685
&implicit_return::IMPLICIT_RETURN,
684686
&implicit_saturating_sub::IMPLICIT_SATURATING_SUB,
685687
&inconsistent_struct_constructor::INCONSISTENT_STRUCT_CONSTRUCTOR,
@@ -1280,6 +1282,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
12801282
store.register_late_pass(|| box redundant_slicing::RedundantSlicing);
12811283
store.register_late_pass(|| box from_str_radix_10::FromStrRadix10);
12821284
store.register_late_pass(|| box manual_map::ManualMap);
1285+
store.register_late_pass(move || box if_then_some_else_none::IfThenSomeElseNone::new(msrv));
12831286

12841287
store.register_group(true, "clippy::restriction", Some("clippy_restriction"), vec![
12851288
LintId::of(&arithmetic::FLOAT_ARITHMETIC),
@@ -1295,6 +1298,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
12951298
LintId::of(&exhaustive_items::EXHAUSTIVE_STRUCTS),
12961299
LintId::of(&exit::EXIT),
12971300
LintId::of(&float_literal::LOSSY_FLOAT_LITERAL),
1301+
LintId::of(&if_then_some_else_none::IF_THEN_SOME_ELSE_NONE),
12981302
LintId::of(&implicit_return::IMPLICIT_RETURN),
12991303
LintId::of(&indexing_slicing::INDEXING_SLICING),
13001304
LintId::of(&inherent_impl::MULTIPLE_INHERENT_IMPL),

tests/ui/if_then_some_else_none.rs

+104
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
#![warn(clippy::if_then_some_else_none)]
2+
#![feature(custom_inner_attributes)]
3+
4+
fn main() {
5+
// Should issue an error.
6+
let _ = if foo() {
7+
println!("true!");
8+
Some("foo")
9+
} else {
10+
None
11+
};
12+
13+
// Should issue an error when macros are used.
14+
let _ = if matches!(true, true) {
15+
println!("true!");
16+
Some(matches!(true, false))
17+
} else {
18+
None
19+
};
20+
21+
// Should issue an error. Binary expression `o < 32` should be parenthesized.
22+
let x = Some(5);
23+
let _ = x.and_then(|o| if o < 32 { Some(o) } else { None });
24+
25+
// Should issue an error. Unary expression `!x` should be parenthesized.
26+
let x = true;
27+
let _ = if !x { Some(0) } else { None };
28+
29+
// Should not issue an error since the `else` block has a statement besides `None`.
30+
let _ = if foo() {
31+
println!("true!");
32+
Some("foo")
33+
} else {
34+
eprintln!("false...");
35+
None
36+
};
37+
38+
// Should not issue an error since there are more than 2 blocks in the if-else chain.
39+
let _ = if foo() {
40+
println!("foo true!");
41+
Some("foo")
42+
} else if bar() {
43+
println!("bar true!");
44+
Some("bar")
45+
} else {
46+
None
47+
};
48+
49+
let _ = if foo() {
50+
println!("foo true!");
51+
Some("foo")
52+
} else {
53+
bar().then(|| {
54+
println!("bar true!");
55+
"bar"
56+
})
57+
};
58+
59+
// Should not issue an error since the `then` block has `None`, not `Some`.
60+
let _ = if foo() { None } else { Some("foo is false") };
61+
62+
// Should not issue an error since the `else` block doesn't use `None` directly.
63+
let _ = if foo() { Some("foo is true") } else { into_none() };
64+
65+
// Should not issue an error since the `then` block doesn't use `Some` directly.
66+
let _ = if foo() { into_some("foo") } else { None };
67+
}
68+
69+
fn _msrv_1_49() {
70+
#![clippy::msrv = "1.49"]
71+
// `bool::then` was stabilized in 1.50. Do not lint this
72+
let _ = if foo() {
73+
println!("true!");
74+
Some(149)
75+
} else {
76+
None
77+
};
78+
}
79+
80+
fn _msrv_1_50() {
81+
#![clippy::msrv = "1.50"]
82+
let _ = if foo() {
83+
println!("true!");
84+
Some(150)
85+
} else {
86+
None
87+
};
88+
}
89+
90+
fn foo() -> bool {
91+
unimplemented!()
92+
}
93+
94+
fn bar() -> bool {
95+
unimplemented!()
96+
}
97+
98+
fn into_some<T>(v: T) -> Option<T> {
99+
Some(v)
100+
}
101+
102+
fn into_none<T>() -> Option<T> {
103+
None
104+
}
+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
error: this could be simplified with `bool::then`
2+
--> $DIR/if_then_some_else_none.rs:6:13
3+
|
4+
LL | let _ = if foo() {
5+
| _____________^
6+
LL | | println!("true!");
7+
LL | | Some("foo")
8+
LL | | } else {
9+
LL | | None
10+
LL | | };
11+
| |_____^
12+
|
13+
= note: `-D clippy::if-then-some-else-none` implied by `-D warnings`
14+
= help: consider using `bool::then` like: `foo().then(|| { /* snippet */ "foo" })`
15+
16+
error: this could be simplified with `bool::then`
17+
--> $DIR/if_then_some_else_none.rs:14:13
18+
|
19+
LL | let _ = if matches!(true, true) {
20+
| _____________^
21+
LL | | println!("true!");
22+
LL | | Some(matches!(true, false))
23+
LL | | } else {
24+
LL | | None
25+
LL | | };
26+
| |_____^
27+
|
28+
= help: consider using `bool::then` like: `matches!(true, true).then(|| { /* snippet */ matches!(true, false) })`
29+
30+
error: this could be simplified with `bool::then`
31+
--> $DIR/if_then_some_else_none.rs:23:28
32+
|
33+
LL | let _ = x.and_then(|o| if o < 32 { Some(o) } else { None });
34+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
35+
|
36+
= help: consider using `bool::then` like: `(o < 32).then(|| o)`
37+
38+
error: this could be simplified with `bool::then`
39+
--> $DIR/if_then_some_else_none.rs:27:13
40+
|
41+
LL | let _ = if !x { Some(0) } else { None };
42+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
43+
|
44+
= help: consider using `bool::then` like: `(!x).then(|| 0)`
45+
46+
error: this could be simplified with `bool::then`
47+
--> $DIR/if_then_some_else_none.rs:82:13
48+
|
49+
LL | let _ = if foo() {
50+
| _____________^
51+
LL | | println!("true!");
52+
LL | | Some(150)
53+
LL | | } else {
54+
LL | | None
55+
LL | | };
56+
| |_____^
57+
|
58+
= help: consider using `bool::then` like: `foo().then(|| { /* snippet */ 150 })`
59+
60+
error: aborting due to 5 previous errors
61+

0 commit comments

Comments
 (0)