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