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