Skip to content

Commit a672d33

Browse files
committed
Implement new lint: if_then_some_else_none
1 parent 0153679 commit a672d33

File tree

5 files changed

+175
-0
lines changed

5 files changed

+175
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
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
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
use crate::utils;
2+
use if_chain::if_chain;
3+
use rustc_errors::Applicability;
4+
use rustc_hir::{Expr, ExprKind};
5+
use rustc_lint::{LateContext, LateLintPass, LintContext};
6+
use rustc_middle::lint::in_external_macro;
7+
use rustc_session::{declare_lint_pass, declare_tool_lint};
8+
9+
declare_clippy_lint! {
10+
/// **What it does:** Checks for if-else that could be written to `bool::then`.
11+
///
12+
/// **Why is this bad?** Looks a little redundant. Using `bool::then` helps it have less lines of code.
13+
///
14+
/// **Known problems:** None.
15+
///
16+
/// **Example:**
17+
///
18+
/// ```rust
19+
/// # let v = vec![0];
20+
/// let a = if v.is_empty() {
21+
/// println!("true!");
22+
/// Some(42)
23+
/// } else {
24+
/// None
25+
/// };
26+
/// ```
27+
///
28+
/// Could be written:
29+
///
30+
/// ```rust
31+
/// # let v = vec![0];
32+
/// let a = v.is_empty().then(|| {
33+
/// println!("true!");
34+
/// 42
35+
/// });
36+
/// ```
37+
pub IF_THEN_SOME_ELSE_NONE,
38+
restriction,
39+
"Finds if-else that could be written using `bool::then`"
40+
}
41+
42+
declare_lint_pass!(IfThenSomeElseNone => [IF_THEN_SOME_ELSE_NONE]);
43+
44+
impl LateLintPass<'_> for IfThenSomeElseNone {
45+
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'tcx Expr<'_>) {
46+
if in_external_macro(cx.sess(), expr.span) {
47+
return;
48+
}
49+
50+
// We only care about the top-most `if` in the chain
51+
if utils::parent_node_is_if_expr(expr, cx) {
52+
return;
53+
}
54+
55+
if_chain! {
56+
if let ExprKind::If(ref cond, ref then, Some(ref els)) = expr.kind;
57+
if let ExprKind::Block(ref then_block, _) = then.kind;
58+
if let Some(ref then_expr) = then_block.expr;
59+
if let ExprKind::Call(ref then_call, [then_arg]) = then_expr.kind;
60+
if let ExprKind::Path(ref then_call_qpath) = then_call.kind;
61+
if utils::match_qpath(then_call_qpath, &utils::paths::OPTION_SOME);
62+
if let ExprKind::Block(ref els_block, _) = els.kind;
63+
if els_block.stmts.is_empty();
64+
if let Some(ref els_expr) = els_block.expr;
65+
if let ExprKind::Path(ref els_call_qpath) = els_expr.kind;
66+
if utils::match_qpath(els_call_qpath, &utils::paths::OPTION_NONE);
67+
then {
68+
let mut applicability = Applicability::MachineApplicable;
69+
let cond_snip = utils::snippet_with_applicability(cx, cond.span, "[condition]", &mut applicability);
70+
let arg_snip = utils::snippet_with_applicability(cx, then_arg.span, "", &mut applicability);
71+
let sugg = format!(
72+
"{}.then(|| {{ /* snippet */ {} }})",
73+
cond_snip,
74+
arg_snip,
75+
);
76+
utils::span_lint_and_sugg(
77+
cx,
78+
IF_THEN_SOME_ELSE_NONE,
79+
expr.span,
80+
"this could be simplified with `bool::then`",
81+
"try this",
82+
sugg,
83+
applicability,
84+
);
85+
}
86+
}
87+
}
88+
}

clippy_lints/src/lib.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,7 @@ mod identity_op;
230230
mod if_let_mutex;
231231
mod if_let_some_result;
232232
mod if_not_else;
233+
mod if_then_some_else_none;
233234
mod implicit_return;
234235
mod implicit_saturating_sub;
235236
mod inconsistent_struct_constructor;
@@ -667,6 +668,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
667668
&if_let_mutex::IF_LET_MUTEX,
668669
&if_let_some_result::IF_LET_SOME_RESULT,
669670
&if_not_else::IF_NOT_ELSE,
671+
&if_then_some_else_none::IF_THEN_SOME_ELSE_NONE,
670672
&implicit_return::IMPLICIT_RETURN,
671673
&implicit_saturating_sub::IMPLICIT_SATURATING_SUB,
672674
&inconsistent_struct_constructor::INCONSISTENT_STRUCT_CONSTRUCTOR,
@@ -1282,6 +1284,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
12821284
store.register_late_pass(|| box redundant_slicing::RedundantSlicing);
12831285
store.register_late_pass(|| box from_str_radix_10::FromStrRadix10);
12841286
store.register_late_pass(|| box manual_map::ManualMap);
1287+
store.register_late_pass(|| box if_then_some_else_none::IfThenSomeElseNone);
12851288

12861289
store.register_group(true, "clippy::restriction", Some("clippy_restriction"), vec![
12871290
LintId::of(&arithmetic::FLOAT_ARITHMETIC),
@@ -1297,6 +1300,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
12971300
LintId::of(&exhaustive_items::EXHAUSTIVE_STRUCTS),
12981301
LintId::of(&exit::EXIT),
12991302
LintId::of(&float_literal::LOSSY_FLOAT_LITERAL),
1303+
LintId::of(&if_then_some_else_none::IF_THEN_SOME_ELSE_NONE),
13001304
LintId::of(&implicit_return::IMPLICIT_RETURN),
13011305
LintId::of(&indexing_slicing::INDEXING_SLICING),
13021306
LintId::of(&inherent_impl::MULTIPLE_INHERENT_IMPL),

tests/ui/if_then_some_else_none.rs

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#![warn(clippy::if_then_some_else_none)]
2+
3+
fn main() {
4+
// Should issue an error.
5+
let _ = if foo() {
6+
println!("true!");
7+
Some("foo")
8+
} else {
9+
None
10+
};
11+
12+
// Should not issue an error since the `else` block has a statement besides `None`.
13+
let _ = if foo() {
14+
println!("true!");
15+
Some("foo")
16+
} else {
17+
eprintln!("false...");
18+
None
19+
};
20+
21+
// Should not issue an error since there are more than 2 blocks in the if-else chain.
22+
let _ = if foo() {
23+
println!("foo true!");
24+
Some("foo")
25+
} else if bar() {
26+
println!("bar true!");
27+
Some("bar")
28+
} else {
29+
None
30+
};
31+
32+
let _ = if foo() {
33+
println!("foo true!");
34+
Some("foo")
35+
} else {
36+
bar().then(|| {
37+
println!("bar true!");
38+
"bar"
39+
})
40+
};
41+
42+
// Should not issue an error since the `then` block has `None`, not `Some`.
43+
let _ = if foo() { None } else { Some("foo is false") };
44+
45+
// Should not issue an error since the `else` block doesn't use `None` directly.
46+
let _ = if foo() { Some("foo is true") } else { into_none() };
47+
48+
// Should not issue an error since the `then` block doesn't use `Some` directly.
49+
let _ = if foo() { into_some("foo") } else { None };
50+
}
51+
52+
fn foo() -> bool {
53+
unimplemented!()
54+
}
55+
56+
fn bar() -> bool {
57+
unimplemented!()
58+
}
59+
60+
fn into_some<T>(v: T) -> Option<T> {
61+
Some(v)
62+
}
63+
64+
fn into_none<T>() -> Option<T> {
65+
None
66+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
error: this could be simplified with `bool::then`
2+
--> $DIR/if_then_some_else_none.rs:5: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+
| |_____^ help: try this: `foo().then(|| { /* snippet */ "foo" })`
12+
|
13+
= note: `-D clippy::if-then-some-else-none` implied by `-D warnings`
14+
15+
error: aborting due to previous error
16+

0 commit comments

Comments
 (0)