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