]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/equatable_if_let.rs
Rollup merge of #89642 - devnexen:macos_getenv_chng, r=m-ou-se
[rust.git] / src / tools / clippy / clippy_lints / src / equatable_if_let.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_with_context;
3 use clippy_utils::ty::implements_trait;
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::{Expr, ExprKind, Pat, PatKind};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_middle::ty::Ty;
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10
11 declare_clippy_lint! {
12     /// ### What it does
13     /// Checks for pattern matchings that can be expressed using equality.
14     ///
15     /// ### Why is this bad?
16     ///
17     /// * It reads better and has less cognitive load because equality won't cause binding.
18     /// * It is a [Yoda condition](https://en.wikipedia.org/wiki/Yoda_conditions). Yoda conditions are widely
19     /// criticized for increasing the cognitive load of reading the code.
20     /// * Equality is a simple bool expression and can be merged with `&&` and `||` and
21     /// reuse if blocks
22     ///
23     /// ### Example
24     /// ```rust,ignore
25     /// if let Some(2) = x {
26     ///     do_thing();
27     /// }
28     /// ```
29     /// Should be written
30     /// ```rust,ignore
31     /// if x == Some(2) {
32     ///     do_thing();
33     /// }
34     /// ```
35     pub EQUATABLE_IF_LET,
36     nursery,
37     "using pattern matching instead of equality"
38 }
39
40 declare_lint_pass!(PatternEquality => [EQUATABLE_IF_LET]);
41
42 /// detects if pattern matches just one thing
43 fn unary_pattern(pat: &Pat<'_>) -> bool {
44     fn array_rec(pats: &[Pat<'_>]) -> bool {
45         pats.iter().all(unary_pattern)
46     }
47     match &pat.kind {
48         PatKind::Slice(_, _, _) | PatKind::Range(_, _, _) | PatKind::Binding(..) | PatKind::Wild | PatKind::Or(_) => {
49             false
50         },
51         PatKind::Struct(_, a, etc) => !etc && a.iter().all(|x| unary_pattern(x.pat)),
52         PatKind::Tuple(a, etc) | PatKind::TupleStruct(_, a, etc) => !etc.is_some() && array_rec(a),
53         PatKind::Ref(x, _) | PatKind::Box(x) => unary_pattern(x),
54         PatKind::Path(_) | PatKind::Lit(_) => true,
55     }
56 }
57
58 fn is_structural_partial_eq(cx: &LateContext<'tcx>, ty: Ty<'tcx>, other: Ty<'tcx>) -> bool {
59     if let Some(def_id) = cx.tcx.lang_items().eq_trait() {
60         implements_trait(cx, ty, def_id, &[other.into()])
61     } else {
62         false
63     }
64 }
65
66 impl<'tcx> LateLintPass<'tcx> for PatternEquality {
67     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
68         if_chain! {
69             if let ExprKind::Let(pat, exp, _) = expr.kind;
70             if unary_pattern(pat);
71             let exp_ty = cx.typeck_results().expr_ty(exp);
72             let pat_ty = cx.typeck_results().pat_ty(pat);
73             if is_structural_partial_eq(cx, exp_ty, pat_ty);
74             then {
75
76                 let mut applicability = Applicability::MachineApplicable;
77                 let pat_str = match pat.kind {
78                     PatKind::Struct(..) => format!(
79                         "({})",
80                         snippet_with_context(cx, pat.span, expr.span.ctxt(), "..", &mut applicability).0,
81                     ),
82                     _ => snippet_with_context(cx, pat.span, expr.span.ctxt(), "..", &mut applicability).0.to_string(),
83                 };
84                 span_lint_and_sugg(
85                     cx,
86                     EQUATABLE_IF_LET,
87                     expr.span,
88                     "this pattern matching can be expressed using equality",
89                     "try",
90                     format!(
91                         "{} == {}",
92                         snippet_with_context(cx, exp.span, expr.span.ctxt(), "..", &mut applicability).0,
93                         pat_str,
94                     ),
95                     applicability,
96                 );
97             }
98         }
99     }
100 }