]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/eq_op.rs
Auto merge of #6828 - mgacek8:issue_6758_enhance_wrong_self_convention, r=flip1995
[rust.git] / clippy_lints / src / eq_op.rs
1 use crate::utils::{
2     ast_utils::is_useless_with_eq_exprs, eq_expr_value, higher, in_macro, is_expn_of, multispan_sugg, snippet,
3     span_lint, span_lint_and_then,
4 };
5 use clippy_utils::ty::{implements_trait, is_copy};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BinOpKind, BorrowKind, Expr, ExprKind, StmtKind};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11
12 declare_clippy_lint! {
13     /// **What it does:** Checks for equal operands to comparison, logical and
14     /// bitwise, difference and division binary operators (`==`, `>`, etc., `&&`,
15     /// `||`, `&`, `|`, `^`, `-` and `/`).
16     ///
17     /// **Why is this bad?** This is usually just a typo or a copy and paste error.
18     ///
19     /// **Known problems:** False negatives: We had some false positives regarding
20     /// calls (notably [racer](https://github.com/phildawes/racer) had one instance
21     /// of `x.pop() && x.pop()`), so we removed matching any function or method
22     /// calls. We may introduce a list of known pure functions in the future.
23     ///
24     /// **Example:**
25     /// ```rust
26     /// # let x = 1;
27     /// if x + 1 == x + 1 {}
28     /// ```
29     /// or
30     /// ```rust
31     /// # let a = 3;
32     /// # let b = 4;
33     /// assert_eq!(a, a);
34     /// ```
35     pub EQ_OP,
36     correctness,
37     "equal operands on both sides of a comparison or bitwise combination (e.g., `x == x`)"
38 }
39
40 declare_clippy_lint! {
41     /// **What it does:** Checks for arguments to `==` which have their address
42     /// taken to satisfy a bound
43     /// and suggests to dereference the other argument instead
44     ///
45     /// **Why is this bad?** It is more idiomatic to dereference the other argument.
46     ///
47     /// **Known problems:** None
48     ///
49     /// **Example:**
50     /// ```ignore
51     /// // Bad
52     /// &x == y
53     ///
54     /// // Good
55     /// x == *y
56     /// ```
57     pub OP_REF,
58     style,
59     "taking a reference to satisfy the type constraints on `==`"
60 }
61
62 declare_lint_pass!(EqOp => [EQ_OP, OP_REF]);
63
64 const ASSERT_MACRO_NAMES: [&str; 4] = ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne"];
65
66 impl<'tcx> LateLintPass<'tcx> for EqOp {
67     #[allow(clippy::similar_names, clippy::too_many_lines)]
68     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
69         if let ExprKind::Block(ref block, _) = e.kind {
70             for stmt in block.stmts {
71                 for amn in &ASSERT_MACRO_NAMES {
72                     if_chain! {
73                         if is_expn_of(stmt.span, amn).is_some();
74                         if let StmtKind::Semi(ref matchexpr) = stmt.kind;
75                         if let Some(macro_args) = higher::extract_assert_macro_args(matchexpr);
76                         if macro_args.len() == 2;
77                         let (lhs, rhs) = (macro_args[0], macro_args[1]);
78                         if eq_expr_value(cx, lhs, rhs);
79
80                         then {
81                             span_lint(
82                                 cx,
83                                 EQ_OP,
84                                 lhs.span.to(rhs.span),
85                                 &format!("identical args used in this `{}!` macro call", amn),
86                             );
87                         }
88                     }
89                 }
90             }
91         }
92         if let ExprKind::Binary(op, ref left, ref right) = e.kind {
93             if e.span.from_expansion() {
94                 return;
95             }
96             let macro_with_not_op = |expr_kind: &ExprKind<'_>| {
97                 if let ExprKind::Unary(_, ref expr) = *expr_kind {
98                     in_macro(expr.span)
99                 } else {
100                     false
101                 }
102             };
103             if macro_with_not_op(&left.kind) || macro_with_not_op(&right.kind) {
104                 return;
105             }
106             if is_useless_with_eq_exprs(higher::binop(op.node)) && eq_expr_value(cx, left, right) {
107                 span_lint(
108                     cx,
109                     EQ_OP,
110                     e.span,
111                     &format!("equal expressions as operands to `{}`", op.node.as_str()),
112                 );
113                 return;
114             }
115             let (trait_id, requires_ref) = match op.node {
116                 BinOpKind::Add => (cx.tcx.lang_items().add_trait(), false),
117                 BinOpKind::Sub => (cx.tcx.lang_items().sub_trait(), false),
118                 BinOpKind::Mul => (cx.tcx.lang_items().mul_trait(), false),
119                 BinOpKind::Div => (cx.tcx.lang_items().div_trait(), false),
120                 BinOpKind::Rem => (cx.tcx.lang_items().rem_trait(), false),
121                 // don't lint short circuiting ops
122                 BinOpKind::And | BinOpKind::Or => return,
123                 BinOpKind::BitXor => (cx.tcx.lang_items().bitxor_trait(), false),
124                 BinOpKind::BitAnd => (cx.tcx.lang_items().bitand_trait(), false),
125                 BinOpKind::BitOr => (cx.tcx.lang_items().bitor_trait(), false),
126                 BinOpKind::Shl => (cx.tcx.lang_items().shl_trait(), false),
127                 BinOpKind::Shr => (cx.tcx.lang_items().shr_trait(), false),
128                 BinOpKind::Ne | BinOpKind::Eq => (cx.tcx.lang_items().eq_trait(), true),
129                 BinOpKind::Lt | BinOpKind::Le | BinOpKind::Ge | BinOpKind::Gt => {
130                     (cx.tcx.lang_items().partial_ord_trait(), true)
131                 },
132             };
133             if let Some(trait_id) = trait_id {
134                 #[allow(clippy::match_same_arms)]
135                 match (&left.kind, &right.kind) {
136                     // do not suggest to dereference literals
137                     (&ExprKind::Lit(..), _) | (_, &ExprKind::Lit(..)) => {},
138                     // &foo == &bar
139                     (&ExprKind::AddrOf(BorrowKind::Ref, _, ref l), &ExprKind::AddrOf(BorrowKind::Ref, _, ref r)) => {
140                         let lty = cx.typeck_results().expr_ty(l);
141                         let rty = cx.typeck_results().expr_ty(r);
142                         let lcpy = is_copy(cx, lty);
143                         let rcpy = is_copy(cx, rty);
144                         // either operator autorefs or both args are copyable
145                         if (requires_ref || (lcpy && rcpy)) && implements_trait(cx, lty, trait_id, &[rty.into()]) {
146                             span_lint_and_then(
147                                 cx,
148                                 OP_REF,
149                                 e.span,
150                                 "needlessly taken reference of both operands",
151                                 |diag| {
152                                     let lsnip = snippet(cx, l.span, "...").to_string();
153                                     let rsnip = snippet(cx, r.span, "...").to_string();
154                                     multispan_sugg(
155                                         diag,
156                                         "use the values directly",
157                                         vec![(left.span, lsnip), (right.span, rsnip)],
158                                     );
159                                 },
160                             )
161                         } else if lcpy
162                             && !rcpy
163                             && implements_trait(cx, lty, trait_id, &[cx.typeck_results().expr_ty(right).into()])
164                         {
165                             span_lint_and_then(
166                                 cx,
167                                 OP_REF,
168                                 e.span,
169                                 "needlessly taken reference of left operand",
170                                 |diag| {
171                                     let lsnip = snippet(cx, l.span, "...").to_string();
172                                     diag.span_suggestion(
173                                         left.span,
174                                         "use the left value directly",
175                                         lsnip,
176                                         Applicability::MaybeIncorrect, // FIXME #2597
177                                     );
178                                 },
179                             )
180                         } else if !lcpy
181                             && rcpy
182                             && implements_trait(cx, cx.typeck_results().expr_ty(left), trait_id, &[rty.into()])
183                         {
184                             span_lint_and_then(
185                                 cx,
186                                 OP_REF,
187                                 e.span,
188                                 "needlessly taken reference of right operand",
189                                 |diag| {
190                                     let rsnip = snippet(cx, r.span, "...").to_string();
191                                     diag.span_suggestion(
192                                         right.span,
193                                         "use the right value directly",
194                                         rsnip,
195                                         Applicability::MaybeIncorrect, // FIXME #2597
196                                     );
197                                 },
198                             )
199                         }
200                     },
201                     // &foo == bar
202                     (&ExprKind::AddrOf(BorrowKind::Ref, _, ref l), _) => {
203                         let lty = cx.typeck_results().expr_ty(l);
204                         let lcpy = is_copy(cx, lty);
205                         if (requires_ref || lcpy)
206                             && implements_trait(cx, lty, trait_id, &[cx.typeck_results().expr_ty(right).into()])
207                         {
208                             span_lint_and_then(
209                                 cx,
210                                 OP_REF,
211                                 e.span,
212                                 "needlessly taken reference of left operand",
213                                 |diag| {
214                                     let lsnip = snippet(cx, l.span, "...").to_string();
215                                     diag.span_suggestion(
216                                         left.span,
217                                         "use the left value directly",
218                                         lsnip,
219                                         Applicability::MaybeIncorrect, // FIXME #2597
220                                     );
221                                 },
222                             )
223                         }
224                     },
225                     // foo == &bar
226                     (_, &ExprKind::AddrOf(BorrowKind::Ref, _, ref r)) => {
227                         let rty = cx.typeck_results().expr_ty(r);
228                         let rcpy = is_copy(cx, rty);
229                         if (requires_ref || rcpy)
230                             && implements_trait(cx, cx.typeck_results().expr_ty(left), trait_id, &[rty.into()])
231                         {
232                             span_lint_and_then(cx, OP_REF, e.span, "taken reference of right operand", |diag| {
233                                 let rsnip = snippet(cx, r.span, "...").to_string();
234                                 diag.span_suggestion(
235                                     right.span,
236                                     "use the right value directly",
237                                     rsnip,
238                                     Applicability::MaybeIncorrect, // FIXME #2597
239                                 );
240                             })
241                         }
242                     },
243                     _ => {},
244                 }
245             }
246         }
247     }
248 }