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