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