]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/if_then_some_else_none.rs
Rollup merge of #105136 - RalfJung:deref-promotion-comment, r=oli-obk
[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::eager_or_lazy::switch_to_eager_eval;
3 use clippy_utils::msrvs::{self, Msrv};
4 use clippy_utils::source::snippet_with_macro_callsite;
5 use clippy_utils::{contains_return, higher, is_else_clause, is_res_lang_ctor, path_res, peel_blocks};
6 use rustc_hir::LangItem::{OptionNone, OptionSome};
7 use rustc_hir::{Expr, ExprKind, Stmt, StmtKind};
8 use rustc_lint::{LateContext, LateLintPass, LintContext};
9 use rustc_middle::lint::in_external_macro;
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 using either `bool::then` or `bool::then_some`.
15     ///
16     /// ### Why is this bad?
17     /// Looks a little redundant. Using `bool::then` is more concise and incurs no loss of clarity.
18     /// For simple calculations and known values, use `bool::then_some`, which is eagerly evaluated
19     /// in comparison to `bool::then`.
20     ///
21     /// ### Example
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     #[clippy::version = "1.53.0"]
42     pub IF_THEN_SOME_ELSE_NONE,
43     restriction,
44     "Finds if-else that could be written using either `bool::then` or `bool::then_some`"
45 }
46
47 pub struct IfThenSomeElseNone {
48     msrv: Msrv,
49 }
50
51 impl IfThenSomeElseNone {
52     #[must_use]
53     pub fn new(msrv: Msrv) -> Self {
54         Self { msrv }
55     }
56 }
57
58 impl_lint_pass!(IfThenSomeElseNone => [IF_THEN_SOME_ELSE_NONE]);
59
60 impl<'tcx> LateLintPass<'tcx> for IfThenSomeElseNone {
61     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
62         if !self.msrv.meets(msrvs::BOOL_THEN) {
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 let Some(higher::If { cond, then, r#else: Some(els) }) = higher::If::hir(expr)
76             && let ExprKind::Block(then_block, _) = then.kind
77             && let Some(then_expr) = then_block.expr
78             && let ExprKind::Call(then_call, [then_arg]) = then_expr.kind
79             && is_res_lang_ctor(cx, path_res(cx, then_call), OptionSome)
80             && is_res_lang_ctor(cx, path_res(cx, peel_blocks(els)), OptionNone)
81             && !stmts_contains_early_return(then_block.stmts)
82         {
83             let cond_snip = snippet_with_macro_callsite(cx, cond.span, "[condition]");
84             let cond_snip = if matches!(cond.kind, ExprKind::Unary(_, _) | ExprKind::Binary(_, _, _)) {
85                 format!("({cond_snip})")
86             } else {
87                 cond_snip.into_owned()
88             };
89             let arg_snip = snippet_with_macro_callsite(cx, then_arg.span, "");
90             let mut method_body = if then_block.stmts.is_empty() {
91                 arg_snip.into_owned()
92             } else {
93                 format!("{{ /* snippet */ {arg_snip} }}")
94             };
95             let method_name = if switch_to_eager_eval(cx, expr) && self.msrv.meets(msrvs::BOOL_THEN_SOME) {
96                 "then_some"
97             } else {
98                 method_body.insert_str(0, "|| ");
99                 "then"
100             };
101
102             let help = format!(
103                 "consider using `bool::{method_name}` like: `{cond_snip}.{method_name}({method_body})`",
104             );
105             span_lint_and_help(
106                 cx,
107                 IF_THEN_SOME_ELSE_NONE,
108                 expr.span,
109                 &format!("this could be simplified with `bool::{method_name}`"),
110                 None,
111                 &help,
112             );
113         }
114     }
115
116     extract_msrv_attr!(LateContext);
117 }
118
119 fn stmts_contains_early_return(stmts: &[Stmt<'_>]) -> bool {
120     stmts.iter().any(|stmt| {
121         let Stmt { kind: StmtKind::Semi(e), .. } = stmt else { return false };
122
123         contains_return(e)
124     })
125 }