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