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