]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/eq_op.rs
Merge pull request #950 from oli-obk/split3
[rust.git] / clippy_lints / src / eq_op.rs
1 use rustc::hir::*;
2 use rustc::lint::*;
3 use utils::{SpanlessEq, span_lint};
4
5 /// **What it does:** This lint checks for equal operands to comparison, logical and bitwise,
6 /// difference and division binary operators (`==`, `>`, etc., `&&`, `||`, `&`, `|`, `^`, `-` and
7 /// `/`).
8 ///
9 /// **Why is this bad?** This is usually just a typo or a copy and paste error.
10 ///
11 /// **Known problems:** False negatives: We had some false positives regarding calls (notably [racer](https://github.com/phildawes/racer) had one instance of `x.pop() && x.pop()`), so we removed matching any function or method calls. We may introduce a whitelist of known pure functions in the future.
12 ///
13 /// **Example:** `x + 1 == x + 1`
14 declare_lint! {
15     pub EQ_OP,
16     Warn,
17     "equal operands on both sides of a comparison or bitwise combination (e.g. `x == x`)"
18 }
19
20 #[derive(Copy,Clone)]
21 pub struct EqOp;
22
23 impl LintPass for EqOp {
24     fn get_lints(&self) -> LintArray {
25         lint_array!(EQ_OP)
26     }
27 }
28
29 impl LateLintPass for EqOp {
30     fn check_expr(&mut self, cx: &LateContext, e: &Expr) {
31         if let ExprBinary(ref op, ref left, ref right) = e.node {
32             if is_valid_operator(op) && SpanlessEq::new(cx).ignore_fn().eq_expr(left, right) {
33                 span_lint(cx,
34                           EQ_OP,
35                           e.span,
36                           &format!("equal expressions as operands to `{}`", op.node.as_str()));
37             }
38         }
39     }
40 }
41
42
43 fn is_valid_operator(op: &BinOp) -> bool {
44     match op.node {
45         BiSub |
46         BiDiv |
47         BiEq |
48         BiLt |
49         BiLe |
50         BiGt |
51         BiGe |
52         BiNe |
53         BiAnd |
54         BiOr |
55         BiBitXor |
56         BiBitAnd |
57         BiBitOr => true,
58         _ => false,
59     }
60 }