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