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