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