]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/eq_op.rs
BinOpKind
[rust.git] / clippy_lints / src / eq_op.rs
1 use rustc::hir::*;
2 use rustc::lint::*;
3 use crate::utils::{in_macro, implements_trait, is_copy, multispan_sugg, snippet, span_lint, span_lint_and_then, SpanlessEq};
4
5 /// **What it does:** Checks for equal operands to comparison, logical and
6 /// bitwise, difference and division binary operators (`==`, `>`, etc., `&&`,
7 /// `||`, `&`, `|`, `^`, `-` and `/`).
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
12 /// calls (notably [racer](https://github.com/phildawes/racer) had one instance
13 /// of `x.pop() && x.pop()`), so we removed matching any function or method
14 /// calls. We may introduce a whitelist of known pure functions in the future.
15 ///
16 /// **Example:**
17 /// ```rust
18 /// x + 1 == x + 1
19 /// ```
20 declare_clippy_lint! {
21     pub EQ_OP,
22     correctness,
23     "equal operands on both sides of a comparison or bitwise combination (e.g. `x == x`)"
24 }
25
26 /// **What it does:** Checks for arguments to `==` which have their address
27 /// taken to satisfy a bound
28 /// and suggests to dereference the other argument instead
29 ///
30 /// **Why is this bad?** It is more idiomatic to dereference the other argument.
31 ///
32 /// **Known problems:** None
33 ///
34 /// **Example:**
35 /// ```rust
36 /// &x == y
37 /// ```
38 declare_clippy_lint! {
39     pub OP_REF,
40     style,
41     "taking a reference to satisfy the type constraints on `==`"
42 }
43
44 #[derive(Copy, Clone)]
45 pub struct EqOp;
46
47 impl LintPass for EqOp {
48     fn get_lints(&self) -> LintArray {
49         lint_array!(EQ_OP, OP_REF)
50     }
51 }
52
53 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EqOp {
54     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
55         if let ExprKind::Binary(op, ref left, ref right) = e.node {
56             if in_macro(e.span) {
57                 return;
58             }
59             if is_valid_operator(op) && SpanlessEq::new(cx).ignore_fn().eq_expr(left, right) {
60                 span_lint(
61                     cx,
62                     EQ_OP,
63                     e.span,
64                     &format!("equal expressions as operands to `{}`", op.node.as_str()),
65                 );
66                 return;
67             }
68             let (trait_id, requires_ref) = match op.node {
69                 BinOpKind::Add => (cx.tcx.lang_items().add_trait(), false),
70                 BinOpKind::Sub => (cx.tcx.lang_items().sub_trait(), false),
71                 BinOpKind::Mul => (cx.tcx.lang_items().mul_trait(), false),
72                 BinOpKind::Div => (cx.tcx.lang_items().div_trait(), false),
73                 BinOpKind::Rem => (cx.tcx.lang_items().rem_trait(), false),
74                 // don't lint short circuiting ops
75                 BinOpKind::And | BinOpKind::Or => return,
76                 BinOpKind::BitXor => (cx.tcx.lang_items().bitxor_trait(), false),
77                 BinOpKind::BitAnd => (cx.tcx.lang_items().bitand_trait(), false),
78                 BinOpKind::BitOr => (cx.tcx.lang_items().bitor_trait(), false),
79                 BinOpKind::Shl => (cx.tcx.lang_items().shl_trait(), false),
80                 BinOpKind::Shr => (cx.tcx.lang_items().shr_trait(), false),
81                 BinOpKind::Ne | BinOpKind::Eq => (cx.tcx.lang_items().eq_trait(), true),
82                 BinOpKind::Lt | BinOpKind::Le | BinOpKind::Ge | BinOpKind::Gt => (cx.tcx.lang_items().ord_trait(), true),
83             };
84             if let Some(trait_id) = trait_id {
85                 #[allow(match_same_arms)]
86                 match (&left.node, &right.node) {
87                     // do not suggest to dereference literals
88                     (&ExprKind::Lit(..), _) | (_, &ExprKind::Lit(..)) => {},
89                     // &foo == &bar
90                     (&ExprKind::AddrOf(_, ref l), &ExprKind::AddrOf(_, ref r)) => {
91                         let lty = cx.tables.expr_ty(l);
92                         let rty = cx.tables.expr_ty(r);
93                         let lcpy = is_copy(cx, lty);
94                         let rcpy = is_copy(cx, rty);
95                         // either operator autorefs or both args are copyable
96                         if (requires_ref || (lcpy && rcpy)) && implements_trait(cx, lty, trait_id, &[rty.into()]) {
97                             span_lint_and_then(
98                                 cx,
99                                 OP_REF,
100                                 e.span,
101                                 "needlessly taken reference of both operands",
102                                 |db| {
103                                     let lsnip = snippet(cx, l.span, "...").to_string();
104                                     let rsnip = snippet(cx, r.span, "...").to_string();
105                                     multispan_sugg(
106                                         db,
107                                         "use the values directly".to_string(),
108                                         vec![(left.span, lsnip), (right.span, rsnip)],
109                                     );
110                                 },
111                             )
112                         } else if lcpy && !rcpy && implements_trait(cx, lty, trait_id, &[cx.tables.expr_ty(right).into()]) {
113                             span_lint_and_then(cx, OP_REF, e.span, "needlessly taken reference of left operand", |db| {
114                                 let lsnip = snippet(cx, l.span, "...").to_string();
115                                 db.span_suggestion(left.span, "use the left value directly", lsnip);
116                             })
117                         } else if !lcpy && rcpy && implements_trait(cx, cx.tables.expr_ty(left), trait_id, &[rty.into()]) {
118                             span_lint_and_then(
119                                 cx,
120                                 OP_REF,
121                                 e.span,
122                                 "needlessly taken reference of right operand",
123                                 |db| {
124                                     let rsnip = snippet(cx, r.span, "...").to_string();
125                                     db.span_suggestion(right.span, "use the right value directly", rsnip);
126                                 },
127                             )
128                         }
129                     },
130                     // &foo == bar
131                     (&ExprKind::AddrOf(_, ref l), _) => {
132                         let lty = cx.tables.expr_ty(l);
133                         let lcpy = is_copy(cx, lty);
134                         if (requires_ref || lcpy) && implements_trait(cx, lty, trait_id, &[cx.tables.expr_ty(right).into()]) {
135                             span_lint_and_then(cx, OP_REF, e.span, "needlessly taken reference of left operand", |db| {
136                                 let lsnip = snippet(cx, l.span, "...").to_string();
137                                 db.span_suggestion(left.span, "use the left value directly", lsnip);
138                             })
139                         }
140                     },
141                     // foo == &bar
142                     (_, &ExprKind::AddrOf(_, ref r)) => {
143                         let rty = cx.tables.expr_ty(r);
144                         let rcpy = is_copy(cx, rty);
145                         if (requires_ref || rcpy) && implements_trait(cx, cx.tables.expr_ty(left), trait_id, &[rty.into()]) {
146                             span_lint_and_then(cx, OP_REF, e.span, "taken reference of right operand", |db| {
147                                 let rsnip = snippet(cx, r.span, "...").to_string();
148                                 db.span_suggestion(right.span, "use the right value directly", rsnip);
149                             })
150                         }
151                     },
152                     _ => {},
153                 }
154             }
155         }
156     }
157 }
158
159
160 fn is_valid_operator(op: BinOp) -> bool {
161     match op.node {
162         BinOpKind::Sub | BinOpKind::Div | BinOpKind::Eq | BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge | BinOpKind::Ne | BinOpKind::And | BinOpKind::Or | BinOpKind::BitXor | BinOpKind::BitAnd | BinOpKind::BitOr => true,
163         _ => false,
164     }
165 }