1 use crate::utils::{if_sequence, parent_node_is_if_expr, span_help_and_lint, SpanlessEq};
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use rustc::{declare_lint_pass, declare_tool_lint};
7 /// **What it does:** Checks comparison chains written with `if` that can be
8 /// rewritten with `match` and `cmp`.
10 /// **Why is this bad?** `if` is not guaranteed to be exhaustive and conditionals can get
13 /// **Known problems:** None.
20 /// fn f(x: u8, y: u8) {
34 /// use std::cmp::Ordering;
38 /// fn f(x: u8, y: u8) {
40 /// Ordering::Greater => a(),
41 /// Ordering::Less => b(),
42 /// Ordering::Equal => c()
48 "`if`s that can be rewritten with `match` and `cmp`"
51 declare_lint_pass!(ComparisonChain => [COMPARISON_CHAIN]);
53 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ComparisonChain {
54 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
55 if expr.span.from_expansion() {
59 // We only care about the top-most `if` in the chain
60 if parent_node_is_if_expr(expr, cx) {
64 // Check that there exists at least one explicit else condition
65 let (conds, _) = if_sequence(expr);
70 for cond in conds.windows(2) {
72 &ExprKind::Binary(ref kind1, ref lhs1, ref rhs1),
73 &ExprKind::Binary(ref kind2, ref lhs2, ref rhs2),
74 ) = (&cond[0].kind, &cond[1].kind)
76 if !kind_is_cmp(kind1.node) || !kind_is_cmp(kind2.node) {
80 // Check that both sets of operands are equal
81 let mut spanless_eq = SpanlessEq::new(cx);
82 if (!spanless_eq.eq_expr(lhs1, lhs2) || !spanless_eq.eq_expr(rhs1, rhs2))
83 && (!spanless_eq.eq_expr(lhs1, rhs2) || !spanless_eq.eq_expr(rhs1, lhs2))
88 // We only care about comparison chains
96 "`if` chain can be rewritten with `match`",
97 "Consider rewriting the `if` chain to use `cmp` and `match`.",
102 fn kind_is_cmp(kind: BinOpKind) -> bool {
104 BinOpKind::Lt | BinOpKind::Gt | BinOpKind::Eq => true,