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, in_constant, is_else_clause, 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};
9 /// **What it does:** Checks comparison chains written with `if` that can be
10 /// rewritten with `match` and `cmp`.
12 /// **Why is this bad?** `if` is not guaranteed to be exhaustive and conditionals can get
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)
23 /// fn f(x: u8, y: u8) {
37 /// use std::cmp::Ordering;
41 /// fn f(x: u8, y: u8) {
43 /// Ordering::Greater => a(),
44 /// Ordering::Less => b(),
45 /// Ordering::Equal => c()
51 "`if`s that can be rewritten with `match` and `cmp`"
54 declare_lint_pass!(ComparisonChain => [COMPARISON_CHAIN]);
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() {
62 // We only care about the top-most `if` in the chain
63 if is_else_clause(cx.tcx, expr) {
67 if in_constant(cx, expr.hir_id) {
71 // Check that there exists at least one explicit else condition
72 let (conds, _) = if_sequence(expr);
77 for cond in conds.windows(2) {
78 if let (&ExprKind::Binary(ref kind1, lhs1, rhs1), &ExprKind::Binary(ref kind2, lhs2, rhs2)) =
79 (&cond[0].kind, &cond[1].kind)
81 if !kind_is_cmp(kind1.node) || !kind_is_cmp(kind2.node) {
85 // Check that both sets of operands are equal
86 let mut spanless_eq = SpanlessEq::new(cx);
87 let same_fixed_operands = spanless_eq.eq_expr(lhs1, lhs2) && spanless_eq.eq_expr(rhs1, rhs2);
88 let same_transposed_operands = spanless_eq.eq_expr(lhs1, rhs2) && spanless_eq.eq_expr(rhs1, lhs2);
90 if !same_fixed_operands && !same_transposed_operands {
94 // Check that if the operation is the same, either it's not `==` or the operands are transposed
95 if kind1.node == kind2.node {
96 if kind1.node == BinOpKind::Eq {
99 if !same_transposed_operands {
104 // Check that the type being compared implements `core::cmp::Ord`
105 let ty = cx.typeck_results().expr_ty(lhs1);
106 let is_ord = get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[]));
112 // We only care about comparison chains
120 "`if` chain can be rewritten with `match`",
122 "consider rewriting the `if` chain to use `cmp` and `match`",
127 fn kind_is_cmp(kind: BinOpKind) -> bool {
128 matches!(kind, BinOpKind::Lt | BinOpKind::Gt | BinOpKind::Eq)