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