]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/if_then_some_else_none.rs
New upstream version 1.66.0+dfsg1
[rustc.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::source::snippet_with_macro_callsite;
4 use clippy_utils::{
5 contains_return, higher, is_else_clause, is_res_lang_ctor, meets_msrv, msrvs, path_res, peel_blocks,
6 };
7 use rustc_hir::LangItem::{OptionNone, OptionSome};
8 use rustc_hir::{Expr, ExprKind, Stmt, StmtKind};
9 use rustc_lint::{LateContext, LateLintPass, LintContext};
10 use rustc_middle::lint::in_external_macro;
11 use rustc_semver::RustcVersion;
12 use rustc_session::{declare_tool_lint, impl_lint_pass};
13
14 declare_clippy_lint! {
15 /// ### What it does
16 /// Checks for if-else that could be written using either `bool::then` or `bool::then_some`.
17 ///
18 /// ### Why is this bad?
19 /// Looks a little redundant. Using `bool::then` is more concise and incurs no loss of clarity.
20 /// For simple calculations and known values, use `bool::then_some`, which is eagerly evaluated
21 /// in comparison to `bool::then`.
22 ///
23 /// ### Example
24 /// ```rust
25 /// # let v = vec![0];
26 /// let a = if v.is_empty() {
27 /// println!("true!");
28 /// Some(42)
29 /// } else {
30 /// None
31 /// };
32 /// ```
33 ///
34 /// Could be written:
35 ///
36 /// ```rust
37 /// # let v = vec![0];
38 /// let a = v.is_empty().then(|| {
39 /// println!("true!");
40 /// 42
41 /// });
42 /// ```
43 #[clippy::version = "1.53.0"]
44 pub IF_THEN_SOME_ELSE_NONE,
45 restriction,
46 "Finds if-else that could be written using either `bool::then` or `bool::then_some`"
47 }
48
49 pub struct IfThenSomeElseNone {
50 msrv: Option<RustcVersion>,
51 }
52
53 impl IfThenSomeElseNone {
54 #[must_use]
55 pub fn new(msrv: Option<RustcVersion>) -> Self {
56 Self { msrv }
57 }
58 }
59
60 impl_lint_pass!(IfThenSomeElseNone => [IF_THEN_SOME_ELSE_NONE]);
61
62 impl<'tcx> LateLintPass<'tcx> for IfThenSomeElseNone {
63 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
64 if !meets_msrv(self.msrv, msrvs::BOOL_THEN) {
65 return;
66 }
67
68 if in_external_macro(cx.sess(), expr.span) {
69 return;
70 }
71
72 // We only care about the top-most `if` in the chain
73 if is_else_clause(cx.tcx, expr) {
74 return;
75 }
76
77 if let Some(higher::If { cond, then, r#else: Some(els) }) = higher::If::hir(expr)
78 && let ExprKind::Block(then_block, _) = then.kind
79 && let Some(then_expr) = then_block.expr
80 && let ExprKind::Call(then_call, [then_arg]) = then_expr.kind
81 && is_res_lang_ctor(cx, path_res(cx, then_call), OptionSome)
82 && is_res_lang_ctor(cx, path_res(cx, peel_blocks(els)), OptionNone)
83 && !stmts_contains_early_return(then_block.stmts)
84 {
85 let cond_snip = snippet_with_macro_callsite(cx, cond.span, "[condition]");
86 let cond_snip = if matches!(cond.kind, ExprKind::Unary(_, _) | ExprKind::Binary(_, _, _)) {
87 format!("({cond_snip})")
88 } else {
89 cond_snip.into_owned()
90 };
91 let arg_snip = snippet_with_macro_callsite(cx, then_arg.span, "");
92 let mut method_body = if then_block.stmts.is_empty() {
93 arg_snip.into_owned()
94 } else {
95 format!("{{ /* snippet */ {arg_snip} }}")
96 };
97 let method_name = if switch_to_eager_eval(cx, expr) && meets_msrv(self.msrv, msrvs::BOOL_THEN_SOME) {
98 "then_some"
99 } else {
100 method_body.insert_str(0, "|| ");
101 "then"
102 };
103
104 let help = format!(
105 "consider using `bool::{method_name}` like: `{cond_snip}.{method_name}({method_body})`",
106 );
107 span_lint_and_help(
108 cx,
109 IF_THEN_SOME_ELSE_NONE,
110 expr.span,
111 &format!("this could be simplified with `bool::{method_name}`"),
112 None,
113 &help,
114 );
115 }
116 }
117
118 extract_msrv_attr!(LateContext);
119 }
120
121 fn stmts_contains_early_return(stmts: &[Stmt<'_>]) -> bool {
122 stmts.iter().any(|stmt| {
123 let Stmt { kind: StmtKind::Semi(e), .. } = stmt else { return false };
124
125 contains_return(e)
126 })
127 }