]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/if_then_some_else_none.rs
Rollup merge of #96336 - Nilstrieb:link-to-correct-as_mut-in-ptr-as_ref, r=JohnTitor
[rust.git] / src / tools / clippy / 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::{contains_return, higher, is_else_clause, is_lang_ctor, meets_msrv, msrvs, peel_blocks};
4 use if_chain::if_chain;
5 use rustc_hir::LangItem::{OptionNone, OptionSome};
6 use rustc_hir::{Expr, ExprKind, Stmt, StmtKind};
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 declare_clippy_lint! {
13     /// ### What it does
14     /// Checks for if-else that could be written to `bool::then`.
15     ///
16     /// ### Why is this bad?
17     /// Looks a little redundant. Using `bool::then` helps it have less lines of code.
18     ///
19     /// ### Example
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     #[clippy::version = "1.53.0"]
40     pub IF_THEN_SOME_ELSE_NONE,
41     restriction,
42     "Finds if-else that could be written using `bool::then`"
43 }
44
45 pub struct IfThenSomeElseNone {
46     msrv: Option<RustcVersion>,
47 }
48
49 impl IfThenSomeElseNone {
50     #[must_use]
51     pub fn new(msrv: Option<RustcVersion>) -> Self {
52         Self { msrv }
53     }
54 }
55
56 impl_lint_pass!(IfThenSomeElseNone => [IF_THEN_SOME_ELSE_NONE]);
57
58 impl<'tcx> LateLintPass<'tcx> for IfThenSomeElseNone {
59     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'tcx Expr<'_>) {
60         if !meets_msrv(self.msrv.as_ref(), &msrvs::BOOL_THEN) {
61             return;
62         }
63
64         if in_external_macro(cx.sess(), expr.span) {
65             return;
66         }
67
68         // We only care about the top-most `if` in the chain
69         if is_else_clause(cx.tcx, expr) {
70             return;
71         }
72
73         if_chain! {
74             if let Some(higher::If { cond, then, r#else: Some(els) }) = higher::If::hir(expr);
75             if let ExprKind::Block(then_block, _) = then.kind;
76             if let Some(then_expr) = then_block.expr;
77             if let ExprKind::Call(then_call, [then_arg]) = then_expr.kind;
78             if let ExprKind::Path(ref then_call_qpath) = then_call.kind;
79             if is_lang_ctor(cx, then_call_qpath, OptionSome);
80             if let ExprKind::Path(ref qpath) = peel_blocks(els).kind;
81             if is_lang_ctor(cx, qpath, OptionNone);
82             if !stmts_contains_early_return(then_block.stmts);
83             then {
84                 let cond_snip = snippet_with_macro_callsite(cx, cond.span, "[condition]");
85                 let cond_snip = if matches!(cond.kind, ExprKind::Unary(_, _) | ExprKind::Binary(_, _, _)) {
86                     format!("({})", cond_snip)
87                 } else {
88                     cond_snip.into_owned()
89                 };
90                 let arg_snip = snippet_with_macro_callsite(cx, then_arg.span, "");
91                 let closure_body = if then_block.stmts.is_empty() {
92                     arg_snip.into_owned()
93                 } else {
94                     format!("{{ /* snippet */ {} }}", arg_snip)
95                 };
96                 let help = format!(
97                     "consider using `bool::then` like: `{}.then(|| {})`",
98                     cond_snip,
99                     closure_body,
100                 );
101                 span_lint_and_help(
102                     cx,
103                     IF_THEN_SOME_ELSE_NONE,
104                     expr.span,
105                     "this could be simplified with `bool::then`",
106                     None,
107                     &help,
108                 );
109             }
110         }
111     }
112
113     extract_msrv_attr!(LateContext);
114 }
115
116 fn stmts_contains_early_return(stmts: &[Stmt<'_>]) -> bool {
117     stmts.iter().any(|stmt| {
118         let Stmt { kind: StmtKind::Semi(e), .. } = stmt else { return false };
119
120         contains_return(e)
121     })
122 }