]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/eq_op.rs
Auto merge of #4962 - JohnTitor:rustup-1227, r=matthiaskrgr
[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::declare_lint_pass;
3 use rustc::hir::*;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc_errors::Applicability;
6 use rustc_session::declare_tool_lint;
7
8 declare_clippy_lint! {
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     /// # let x = 1;
23     /// if x + 1 == x + 1 {}
24     /// ```
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 declare_clippy_lint! {
31     /// **What it does:** Checks for arguments to `==` which have their address
32     /// taken to satisfy a bound
33     /// and suggests to dereference the other argument instead
34     ///
35     /// **Why is this bad?** It is more idiomatic to dereference the other argument.
36     ///
37     /// **Known problems:** None
38     ///
39     /// **Example:**
40     /// ```ignore
41     /// &x == y
42     /// ```
43     pub OP_REF,
44     style,
45     "taking a reference to satisfy the type constraints on `==`"
46 }
47
48 declare_lint_pass!(EqOp => [EQ_OP, OP_REF]);
49
50 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EqOp {
51     #[allow(clippy::similar_names, clippy::too_many_lines)]
52     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) {
53         if let ExprKind::Binary(op, ref left, ref right) = e.kind {
54             if e.span.from_expansion() {
55                 return;
56             }
57             if is_valid_operator(op) && SpanlessEq::new(cx).ignore_fn().eq_expr(left, right) {
58                 span_lint(
59                     cx,
60                     EQ_OP,
61                     e.span,
62                     &format!("equal expressions as operands to `{}`", op.node.as_str()),
63                 );
64                 return;
65             }
66             let (trait_id, requires_ref) = match op.node {
67                 BinOpKind::Add => (cx.tcx.lang_items().add_trait(), false),
68                 BinOpKind::Sub => (cx.tcx.lang_items().sub_trait(), false),
69                 BinOpKind::Mul => (cx.tcx.lang_items().mul_trait(), false),
70                 BinOpKind::Div => (cx.tcx.lang_items().div_trait(), false),
71                 BinOpKind::Rem => (cx.tcx.lang_items().rem_trait(), false),
72                 // don't lint short circuiting ops
73                 BinOpKind::And | BinOpKind::Or => return,
74                 BinOpKind::BitXor => (cx.tcx.lang_items().bitxor_trait(), false),
75                 BinOpKind::BitAnd => (cx.tcx.lang_items().bitand_trait(), false),
76                 BinOpKind::BitOr => (cx.tcx.lang_items().bitor_trait(), false),
77                 BinOpKind::Shl => (cx.tcx.lang_items().shl_trait(), false),
78                 BinOpKind::Shr => (cx.tcx.lang_items().shr_trait(), false),
79                 BinOpKind::Ne | BinOpKind::Eq => (cx.tcx.lang_items().eq_trait(), true),
80                 BinOpKind::Lt | BinOpKind::Le | BinOpKind::Ge | BinOpKind::Gt => {
81                     (cx.tcx.lang_items().partial_ord_trait(), true)
82                 },
83             };
84             if let Some(trait_id) = trait_id {
85                 #[allow(clippy::match_same_arms)]
86                 match (&left.kind, &right.kind) {
87                     // do not suggest to dereference literals
88                     (&ExprKind::Lit(..), _) | (_, &ExprKind::Lit(..)) => {},
89                     // &foo == &bar
90                     (&ExprKind::AddrOf(BorrowKind::Ref, _, ref l), &ExprKind::AddrOf(BorrowKind::Ref, _, ref r)) => {
91                         let lty = cx.tables.expr_ty(l);
92                         let rty = cx.tables.expr_ty(r);
93                         let lcpy = is_copy(cx, lty);
94                         let rcpy = is_copy(cx, rty);
95                         // either operator autorefs or both args are copyable
96                         if (requires_ref || (lcpy && rcpy)) && implements_trait(cx, lty, trait_id, &[rty.into()]) {
97                             span_lint_and_then(
98                                 cx,
99                                 OP_REF,
100                                 e.span,
101                                 "needlessly taken reference of both operands",
102                                 |db| {
103                                     let lsnip = snippet(cx, l.span, "...").to_string();
104                                     let rsnip = snippet(cx, r.span, "...").to_string();
105                                     multispan_sugg(
106                                         db,
107                                         "use the values directly".to_string(),
108                                         vec![(left.span, lsnip), (right.span, rsnip)],
109                                     );
110                                 },
111                             )
112                         } else if lcpy
113                             && !rcpy
114                             && implements_trait(cx, lty, trait_id, &[cx.tables.expr_ty(right).into()])
115                         {
116                             span_lint_and_then(cx, OP_REF, e.span, "needlessly taken reference of left operand", |db| {
117                                 let lsnip = snippet(cx, l.span, "...").to_string();
118                                 db.span_suggestion(
119                                     left.span,
120                                     "use the left value directly",
121                                     lsnip,
122                                     Applicability::MaybeIncorrect, // FIXME #2597
123                                 );
124                             })
125                         } else if !lcpy
126                             && rcpy
127                             && implements_trait(cx, cx.tables.expr_ty(left), trait_id, &[rty.into()])
128                         {
129                             span_lint_and_then(
130                                 cx,
131                                 OP_REF,
132                                 e.span,
133                                 "needlessly taken reference of right operand",
134                                 |db| {
135                                     let rsnip = snippet(cx, r.span, "...").to_string();
136                                     db.span_suggestion(
137                                         right.span,
138                                         "use the right value directly",
139                                         rsnip,
140                                         Applicability::MaybeIncorrect, // FIXME #2597
141                                     );
142                                 },
143                             )
144                         }
145                     },
146                     // &foo == bar
147                     (&ExprKind::AddrOf(BorrowKind::Ref, _, ref l), _) => {
148                         let lty = cx.tables.expr_ty(l);
149                         let lcpy = is_copy(cx, lty);
150                         if (requires_ref || lcpy)
151                             && implements_trait(cx, lty, trait_id, &[cx.tables.expr_ty(right).into()])
152                         {
153                             span_lint_and_then(cx, OP_REF, e.span, "needlessly taken reference of left operand", |db| {
154                                 let lsnip = snippet(cx, l.span, "...").to_string();
155                                 db.span_suggestion(
156                                     left.span,
157                                     "use the left value directly",
158                                     lsnip,
159                                     Applicability::MaybeIncorrect, // FIXME #2597
160                                 );
161                             })
162                         }
163                     },
164                     // foo == &bar
165                     (_, &ExprKind::AddrOf(BorrowKind::Ref, _, ref r)) => {
166                         let rty = cx.tables.expr_ty(r);
167                         let rcpy = is_copy(cx, rty);
168                         if (requires_ref || rcpy)
169                             && implements_trait(cx, cx.tables.expr_ty(left), trait_id, &[rty.into()])
170                         {
171                             span_lint_and_then(cx, OP_REF, e.span, "taken reference of right operand", |db| {
172                                 let rsnip = snippet(cx, r.span, "...").to_string();
173                                 db.span_suggestion(
174                                     right.span,
175                                     "use the right value directly",
176                                     rsnip,
177                                     Applicability::MaybeIncorrect, // FIXME #2597
178                                 );
179                             })
180                         }
181                     },
182                     _ => {},
183                 }
184             }
185         }
186     }
187 }
188
189 fn is_valid_operator(op: BinOp) -> bool {
190     match op.node {
191         BinOpKind::Sub
192         | BinOpKind::Div
193         | BinOpKind::Eq
194         | BinOpKind::Lt
195         | BinOpKind::Le
196         | BinOpKind::Gt
197         | BinOpKind::Ge
198         | BinOpKind::Ne
199         | BinOpKind::And
200         | BinOpKind::Or
201         | BinOpKind::BitXor
202         | BinOpKind::BitAnd
203         | BinOpKind::BitOr => true,
204         _ => false,
205     }
206 }