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