]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/comparison_chain.rs
Auto merge of #84071 - nagisa:nixos-patching-fix, r=Mark-Simulacrum
[rust.git] / src / tools / clippy / clippy_lints / src / comparison_chain.rs
1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::ty::implements_trait;
3 use clippy_utils::{get_trait_def_id, if_sequence, parent_node_is_if_expr, paths, SpanlessEq};
4 use rustc_hir::{BinOpKind, Expr, ExprKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7
8 declare_clippy_lint! {
9     /// **What it does:** Checks comparison chains written with `if` that can be
10     /// rewritten with `match` and `cmp`.
11     ///
12     /// **Why is this bad?** `if` is not guaranteed to be exhaustive and conditionals can get
13     /// repetitive
14     ///
15     /// **Known problems:** The match statement may be slower due to the compiler
16     /// not inlining the call to cmp. See issue [#5354](https://github.com/rust-lang/rust-clippy/issues/5354)
17     ///
18     /// **Example:**
19     /// ```rust,ignore
20     /// # fn a() {}
21     /// # fn b() {}
22     /// # fn c() {}
23     /// fn f(x: u8, y: u8) {
24     ///     if x > y {
25     ///         a()
26     ///     } else if x < y {
27     ///         b()
28     ///     } else {
29     ///         c()
30     ///     }
31     /// }
32     /// ```
33     ///
34     /// Could be written:
35     ///
36     /// ```rust,ignore
37     /// use std::cmp::Ordering;
38     /// # fn a() {}
39     /// # fn b() {}
40     /// # fn c() {}
41     /// fn f(x: u8, y: u8) {
42     ///      match x.cmp(&y) {
43     ///          Ordering::Greater => a(),
44     ///          Ordering::Less => b(),
45     ///          Ordering::Equal => c()
46     ///      }
47     /// }
48     /// ```
49     pub COMPARISON_CHAIN,
50     style,
51     "`if`s that can be rewritten with `match` and `cmp`"
52 }
53
54 declare_lint_pass!(ComparisonChain => [COMPARISON_CHAIN]);
55
56 impl<'tcx> LateLintPass<'tcx> for ComparisonChain {
57     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
58         if expr.span.from_expansion() {
59             return;
60         }
61
62         // We only care about the top-most `if` in the chain
63         if parent_node_is_if_expr(expr, cx) {
64             return;
65         }
66
67         // Check that there exists at least one explicit else condition
68         let (conds, _) = if_sequence(expr);
69         if conds.len() < 2 {
70             return;
71         }
72
73         for cond in conds.windows(2) {
74             if let (&ExprKind::Binary(ref kind1, lhs1, rhs1), &ExprKind::Binary(ref kind2, lhs2, rhs2)) =
75                 (&cond[0].kind, &cond[1].kind)
76             {
77                 if !kind_is_cmp(kind1.node) || !kind_is_cmp(kind2.node) {
78                     return;
79                 }
80
81                 // Check that both sets of operands are equal
82                 let mut spanless_eq = SpanlessEq::new(cx);
83                 let same_fixed_operands = spanless_eq.eq_expr(lhs1, lhs2) && spanless_eq.eq_expr(rhs1, rhs2);
84                 let same_transposed_operands = spanless_eq.eq_expr(lhs1, rhs2) && spanless_eq.eq_expr(rhs1, lhs2);
85
86                 if !same_fixed_operands && !same_transposed_operands {
87                     return;
88                 }
89
90                 // Check that if the operation is the same, either it's not `==` or the operands are transposed
91                 if kind1.node == kind2.node {
92                     if kind1.node == BinOpKind::Eq {
93                         return;
94                     }
95                     if !same_transposed_operands {
96                         return;
97                     }
98                 }
99
100                 // Check that the type being compared implements `core::cmp::Ord`
101                 let ty = cx.typeck_results().expr_ty(lhs1);
102                 let is_ord = get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[]));
103
104                 if !is_ord {
105                     return;
106                 }
107             } else {
108                 // We only care about comparison chains
109                 return;
110             }
111         }
112         span_lint_and_help(
113             cx,
114             COMPARISON_CHAIN,
115             expr.span,
116             "`if` chain can be rewritten with `match`",
117             None,
118             "consider rewriting the `if` chain to use `cmp` and `match`",
119         )
120     }
121 }
122
123 fn kind_is_cmp(kind: BinOpKind) -> bool {
124     matches!(kind, BinOpKind::Lt | BinOpKind::Gt | BinOpKind::Eq)
125 }