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