]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/eq_op.rs
Merge commit '3d0b0e66afdfaa519d8855b338b35b4605775945' into clippyup
[rust.git] / src / tools / clippy / clippy_lints / src / eq_op.rs
1 use crate::utils::{
2     eq_expr_value, implements_trait, in_macro, is_copy, multispan_sugg, snippet, span_lint, span_lint_and_then,
3 };
4 use rustc_errors::Applicability;
5 use rustc_hir::{BinOp, BinOpKind, BorrowKind, Expr, ExprKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
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 list 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     /// // Bad
43     /// &x == y
44     ///
45     /// // Good
46     /// x == *y
47     /// ```
48     pub OP_REF,
49     style,
50     "taking a reference to satisfy the type constraints on `==`"
51 }
52
53 declare_lint_pass!(EqOp => [EQ_OP, OP_REF]);
54
55 impl<'tcx> LateLintPass<'tcx> for EqOp {
56     #[allow(clippy::similar_names, clippy::too_many_lines)]
57     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
58         if let ExprKind::Binary(op, ref left, ref right) = e.kind {
59             if e.span.from_expansion() {
60                 return;
61             }
62             let macro_with_not_op = |expr_kind: &ExprKind<'_>| {
63                 if let ExprKind::Unary(_, ref expr) = *expr_kind {
64                     in_macro(expr.span)
65                 } else {
66                     false
67                 }
68             };
69             if macro_with_not_op(&left.kind) || macro_with_not_op(&right.kind) {
70                 return;
71             }
72             if is_valid_operator(op) && eq_expr_value(cx, left, right) {
73                 span_lint(
74                     cx,
75                     EQ_OP,
76                     e.span,
77                     &format!("equal expressions as operands to `{}`", op.node.as_str()),
78                 );
79                 return;
80             }
81             let (trait_id, requires_ref) = match op.node {
82                 BinOpKind::Add => (cx.tcx.lang_items().add_trait(), false),
83                 BinOpKind::Sub => (cx.tcx.lang_items().sub_trait(), false),
84                 BinOpKind::Mul => (cx.tcx.lang_items().mul_trait(), false),
85                 BinOpKind::Div => (cx.tcx.lang_items().div_trait(), false),
86                 BinOpKind::Rem => (cx.tcx.lang_items().rem_trait(), false),
87                 // don't lint short circuiting ops
88                 BinOpKind::And | BinOpKind::Or => return,
89                 BinOpKind::BitXor => (cx.tcx.lang_items().bitxor_trait(), false),
90                 BinOpKind::BitAnd => (cx.tcx.lang_items().bitand_trait(), false),
91                 BinOpKind::BitOr => (cx.tcx.lang_items().bitor_trait(), false),
92                 BinOpKind::Shl => (cx.tcx.lang_items().shl_trait(), false),
93                 BinOpKind::Shr => (cx.tcx.lang_items().shr_trait(), false),
94                 BinOpKind::Ne | BinOpKind::Eq => (cx.tcx.lang_items().eq_trait(), true),
95                 BinOpKind::Lt | BinOpKind::Le | BinOpKind::Ge | BinOpKind::Gt => {
96                     (cx.tcx.lang_items().partial_ord_trait(), true)
97                 },
98             };
99             if let Some(trait_id) = trait_id {
100                 #[allow(clippy::match_same_arms)]
101                 match (&left.kind, &right.kind) {
102                     // do not suggest to dereference literals
103                     (&ExprKind::Lit(..), _) | (_, &ExprKind::Lit(..)) => {},
104                     // &foo == &bar
105                     (&ExprKind::AddrOf(BorrowKind::Ref, _, ref l), &ExprKind::AddrOf(BorrowKind::Ref, _, ref r)) => {
106                         let lty = cx.typeck_results().expr_ty(l);
107                         let rty = cx.typeck_results().expr_ty(r);
108                         let lcpy = is_copy(cx, lty);
109                         let rcpy = is_copy(cx, rty);
110                         // either operator autorefs or both args are copyable
111                         if (requires_ref || (lcpy && rcpy)) && implements_trait(cx, lty, trait_id, &[rty.into()]) {
112                             span_lint_and_then(
113                                 cx,
114                                 OP_REF,
115                                 e.span,
116                                 "needlessly taken reference of both operands",
117                                 |diag| {
118                                     let lsnip = snippet(cx, l.span, "...").to_string();
119                                     let rsnip = snippet(cx, r.span, "...").to_string();
120                                     multispan_sugg(
121                                         diag,
122                                         "use the values directly",
123                                         vec![(left.span, lsnip), (right.span, rsnip)],
124                                     );
125                                 },
126                             )
127                         } else if lcpy
128                             && !rcpy
129                             && implements_trait(cx, lty, trait_id, &[cx.typeck_results().expr_ty(right).into()])
130                         {
131                             span_lint_and_then(
132                                 cx,
133                                 OP_REF,
134                                 e.span,
135                                 "needlessly taken reference of left operand",
136                                 |diag| {
137                                     let lsnip = snippet(cx, l.span, "...").to_string();
138                                     diag.span_suggestion(
139                                         left.span,
140                                         "use the left value directly",
141                                         lsnip,
142                                         Applicability::MaybeIncorrect, // FIXME #2597
143                                     );
144                                 },
145                             )
146                         } else if !lcpy
147                             && rcpy
148                             && implements_trait(cx, cx.typeck_results().expr_ty(left), trait_id, &[rty.into()])
149                         {
150                             span_lint_and_then(
151                                 cx,
152                                 OP_REF,
153                                 e.span,
154                                 "needlessly taken reference of right operand",
155                                 |diag| {
156                                     let rsnip = snippet(cx, r.span, "...").to_string();
157                                     diag.span_suggestion(
158                                         right.span,
159                                         "use the right value directly",
160                                         rsnip,
161                                         Applicability::MaybeIncorrect, // FIXME #2597
162                                     );
163                                 },
164                             )
165                         }
166                     },
167                     // &foo == bar
168                     (&ExprKind::AddrOf(BorrowKind::Ref, _, ref l), _) => {
169                         let lty = cx.typeck_results().expr_ty(l);
170                         let lcpy = is_copy(cx, lty);
171                         if (requires_ref || lcpy)
172                             && implements_trait(cx, lty, trait_id, &[cx.typeck_results().expr_ty(right).into()])
173                         {
174                             span_lint_and_then(
175                                 cx,
176                                 OP_REF,
177                                 e.span,
178                                 "needlessly taken reference of left operand",
179                                 |diag| {
180                                     let lsnip = snippet(cx, l.span, "...").to_string();
181                                     diag.span_suggestion(
182                                         left.span,
183                                         "use the left value directly",
184                                         lsnip,
185                                         Applicability::MaybeIncorrect, // FIXME #2597
186                                     );
187                                 },
188                             )
189                         }
190                     },
191                     // foo == &bar
192                     (_, &ExprKind::AddrOf(BorrowKind::Ref, _, ref r)) => {
193                         let rty = cx.typeck_results().expr_ty(r);
194                         let rcpy = is_copy(cx, rty);
195                         if (requires_ref || rcpy)
196                             && implements_trait(cx, cx.typeck_results().expr_ty(left), trait_id, &[rty.into()])
197                         {
198                             span_lint_and_then(cx, OP_REF, e.span, "taken reference of right operand", |diag| {
199                                 let rsnip = snippet(cx, r.span, "...").to_string();
200                                 diag.span_suggestion(
201                                     right.span,
202                                     "use the right value directly",
203                                     rsnip,
204                                     Applicability::MaybeIncorrect, // FIXME #2597
205                                 );
206                             })
207                         }
208                     },
209                     _ => {},
210                 }
211             }
212         }
213     }
214 }
215
216 fn is_valid_operator(op: BinOp) -> bool {
217     matches!(
218         op.node,
219         BinOpKind::Sub
220             | BinOpKind::Div
221             | BinOpKind::Eq
222             | BinOpKind::Lt
223             | BinOpKind::Le
224             | BinOpKind::Gt
225             | BinOpKind::Ge
226             | BinOpKind::Ne
227             | BinOpKind::And
228             | BinOpKind::Or
229             | BinOpKind::BitXor
230             | BinOpKind::BitAnd
231             | BinOpKind::BitOr
232     )
233 }