]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/eq_op.rs
Merge commit 'd7b5cbf065b88830ca519adcb73fad4c0d24b1c7' into clippyup
[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::get_enclosing_block;
3 use clippy_utils::macros::{find_assert_eq_args, first_node_macro_backtrace};
4 use clippy_utils::source::snippet;
5 use clippy_utils::ty::{implements_trait, is_copy};
6 use clippy_utils::{ast_utils::is_useless_with_eq_exprs, eq_expr_value, is_in_test_function};
7 use if_chain::if_chain;
8 use rustc_errors::Applicability;
9 use rustc_hir::{def::Res, def_id::DefId, BinOpKind, BorrowKind, Expr, ExprKind, GenericArg, ItemKind, QPath, TyKind};
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::ty::{self, Ty};
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13
14 declare_clippy_lint! {
15     /// ### What it does
16     /// Checks for equal operands to comparison, logical and
17     /// bitwise, difference and division binary operators (`==`, `>`, etc., `&&`,
18     /// `||`, `&`, `|`, `^`, `-` and `/`).
19     ///
20     /// ### Why is this bad?
21     /// This is usually just a typo or a copy and paste error.
22     ///
23     /// ### Known problems
24     /// False negatives: We had some false positives regarding
25     /// calls (notably [racer](https://github.com/phildawes/racer) had one instance
26     /// of `x.pop() && x.pop()`), so we removed matching any function or method
27     /// calls. We may introduce a list of known pure functions in the future.
28     ///
29     /// ### Example
30     /// ```rust
31     /// # let x = 1;
32     /// if x + 1 == x + 1 {}
33     ///
34     /// // or
35     ///
36     /// # let a = 3;
37     /// # let b = 4;
38     /// assert_eq!(a, a);
39     /// ```
40     #[clippy::version = "pre 1.29.0"]
41     pub EQ_OP,
42     correctness,
43     "equal operands on both sides of a comparison or bitwise combination (e.g., `x == x`)"
44 }
45
46 declare_clippy_lint! {
47     /// ### What it does
48     /// Checks for arguments to `==` which have their address
49     /// taken to satisfy a bound
50     /// and suggests to dereference the other argument instead
51     ///
52     /// ### Why is this bad?
53     /// It is more idiomatic to dereference the other argument.
54     ///
55     /// ### Example
56     /// ```rust,ignore
57     /// &x == y
58     /// ```
59     ///
60     /// Use instead:
61     /// ```rust,ignore
62     /// x == *y
63     /// ```
64     #[clippy::version = "pre 1.29.0"]
65     pub OP_REF,
66     style,
67     "taking a reference to satisfy the type constraints on `==`"
68 }
69
70 declare_lint_pass!(EqOp => [EQ_OP, OP_REF]);
71
72 impl<'tcx> LateLintPass<'tcx> for EqOp {
73     #[expect(clippy::similar_names, clippy::too_many_lines)]
74     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
75         if_chain! {
76             if let Some((macro_call, macro_name)) = first_node_macro_backtrace(cx, e).find_map(|macro_call| {
77                 let name = cx.tcx.item_name(macro_call.def_id);
78                 matches!(name.as_str(), "assert_eq" | "assert_ne" | "debug_assert_eq" | "debug_assert_ne")
79                     .then(|| (macro_call, name))
80             });
81             if let Some((lhs, rhs, _)) = find_assert_eq_args(cx, e, macro_call.expn);
82             if eq_expr_value(cx, lhs, rhs);
83             if macro_call.is_local();
84             if !is_in_test_function(cx.tcx, e.hir_id);
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", macro_name),
91                 );
92             }
93         }
94         if let ExprKind::Binary(op, left, right) = e.kind {
95             if e.span.from_expansion() {
96                 return;
97             }
98             let macro_with_not_op = |expr_kind: &ExprKind<'_>| {
99                 if let ExprKind::Unary(_, expr) = *expr_kind {
100                     expr.span.from_expansion()
101                 } else {
102                     false
103                 }
104             };
105             if macro_with_not_op(&left.kind) || macro_with_not_op(&right.kind) {
106                 return;
107             }
108             if is_useless_with_eq_exprs(op.node.into())
109                 && eq_expr_value(cx, left, right)
110                 && !is_in_test_function(cx.tcx, e.hir_id)
111             {
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                 match (&left.kind, &right.kind) {
140                     // do not suggest to dereference literals
141                     (&ExprKind::Lit(..), _) | (_, &ExprKind::Lit(..)) => {},
142                     // &foo == &bar
143                     (&ExprKind::AddrOf(BorrowKind::Ref, _, l), &ExprKind::AddrOf(BorrowKind::Ref, _, r)) => {
144                         let lty = cx.typeck_results().expr_ty(l);
145                         let rty = cx.typeck_results().expr_ty(r);
146                         let lcpy = is_copy(cx, lty);
147                         let rcpy = is_copy(cx, rty);
148                         if let Some((self_ty, other_ty)) = in_impl(cx, e, trait_id) {
149                             if (are_equal(cx, rty, self_ty) && are_equal(cx, lty, other_ty))
150                                 || (are_equal(cx, rty, other_ty) && are_equal(cx, lty, self_ty))
151                             {
152                                 return; // Don't lint
153                             }
154                         }
155                         // either operator autorefs or both args are copyable
156                         if (requires_ref || (lcpy && rcpy)) && implements_trait(cx, lty, trait_id, &[rty.into()]) {
157                             span_lint_and_then(
158                                 cx,
159                                 OP_REF,
160                                 e.span,
161                                 "needlessly taken reference of both operands",
162                                 |diag| {
163                                     let lsnip = snippet(cx, l.span, "...").to_string();
164                                     let rsnip = snippet(cx, r.span, "...").to_string();
165                                     multispan_sugg(
166                                         diag,
167                                         "use the values directly",
168                                         vec![(left.span, lsnip), (right.span, rsnip)],
169                                     );
170                                 },
171                             );
172                         } else if lcpy
173                             && !rcpy
174                             && implements_trait(cx, lty, trait_id, &[cx.typeck_results().expr_ty(right).into()])
175                         {
176                             span_lint_and_then(
177                                 cx,
178                                 OP_REF,
179                                 e.span,
180                                 "needlessly taken reference of left operand",
181                                 |diag| {
182                                     let lsnip = snippet(cx, l.span, "...").to_string();
183                                     diag.span_suggestion(
184                                         left.span,
185                                         "use the left value directly",
186                                         lsnip,
187                                         Applicability::MaybeIncorrect, // FIXME #2597
188                                     );
189                                 },
190                             );
191                         } else if !lcpy
192                             && rcpy
193                             && implements_trait(cx, cx.typeck_results().expr_ty(left), trait_id, &[rty.into()])
194                         {
195                             span_lint_and_then(
196                                 cx,
197                                 OP_REF,
198                                 e.span,
199                                 "needlessly taken reference of right operand",
200                                 |diag| {
201                                     let rsnip = snippet(cx, r.span, "...").to_string();
202                                     diag.span_suggestion(
203                                         right.span,
204                                         "use the right value directly",
205                                         rsnip,
206                                         Applicability::MaybeIncorrect, // FIXME #2597
207                                     );
208                                 },
209                             );
210                         }
211                     },
212                     // &foo == bar
213                     (&ExprKind::AddrOf(BorrowKind::Ref, _, l), _) => {
214                         let lty = cx.typeck_results().expr_ty(l);
215                         if let Some((self_ty, other_ty)) = in_impl(cx, e, trait_id) {
216                             let rty = cx.typeck_results().expr_ty(right);
217                             if (are_equal(cx, rty, self_ty) && are_equal(cx, lty, other_ty))
218                                 || (are_equal(cx, rty, other_ty) && are_equal(cx, lty, self_ty))
219                             {
220                                 return; // Don't lint
221                             }
222                         }
223                         let lcpy = is_copy(cx, lty);
224                         if (requires_ref || lcpy)
225                             && implements_trait(cx, lty, trait_id, &[cx.typeck_results().expr_ty(right).into()])
226                         {
227                             span_lint_and_then(
228                                 cx,
229                                 OP_REF,
230                                 e.span,
231                                 "needlessly taken reference of left operand",
232                                 |diag| {
233                                     let lsnip = snippet(cx, l.span, "...").to_string();
234                                     diag.span_suggestion(
235                                         left.span,
236                                         "use the left value directly",
237                                         lsnip,
238                                         Applicability::MaybeIncorrect, // FIXME #2597
239                                     );
240                                 },
241                             );
242                         }
243                     },
244                     // foo == &bar
245                     (_, &ExprKind::AddrOf(BorrowKind::Ref, _, r)) => {
246                         let rty = cx.typeck_results().expr_ty(r);
247                         if let Some((self_ty, other_ty)) = in_impl(cx, e, trait_id) {
248                             let lty = cx.typeck_results().expr_ty(left);
249                             if (are_equal(cx, rty, self_ty) && are_equal(cx, lty, other_ty))
250                                 || (are_equal(cx, rty, other_ty) && are_equal(cx, lty, self_ty))
251                             {
252                                 return; // Don't lint
253                             }
254                         }
255                         let rcpy = is_copy(cx, rty);
256                         if (requires_ref || rcpy)
257                             && implements_trait(cx, cx.typeck_results().expr_ty(left), trait_id, &[rty.into()])
258                         {
259                             span_lint_and_then(cx, OP_REF, e.span, "taken reference of right operand", |diag| {
260                                 let rsnip = snippet(cx, r.span, "...").to_string();
261                                 diag.span_suggestion(
262                                     right.span,
263                                     "use the right value directly",
264                                     rsnip,
265                                     Applicability::MaybeIncorrect, // FIXME #2597
266                                 );
267                             });
268                         }
269                     },
270                     _ => {},
271                 }
272             }
273         }
274     }
275 }
276
277 fn in_impl<'tcx>(
278     cx: &LateContext<'tcx>,
279     e: &'tcx Expr<'_>,
280     bin_op: DefId,
281 ) -> Option<(&'tcx rustc_hir::Ty<'tcx>, &'tcx rustc_hir::Ty<'tcx>)> {
282     if_chain! {
283         if let Some(block) = get_enclosing_block(cx, e.hir_id);
284         if let Some(impl_def_id) = cx.tcx.impl_of_method(block.hir_id.owner.to_def_id());
285         let item = cx.tcx.hir().expect_item(impl_def_id.expect_local());
286         if let ItemKind::Impl(item) = &item.kind;
287         if let Some(of_trait) = &item.of_trait;
288         if let Some(seg) = of_trait.path.segments.last();
289         if let Some(Res::Def(_, trait_id)) = seg.res;
290         if trait_id == bin_op;
291         if let Some(generic_args) = seg.args;
292         if let Some(GenericArg::Type(other_ty)) = generic_args.args.last();
293
294         then {
295             Some((item.self_ty, other_ty))
296         }
297         else {
298             None
299         }
300     }
301 }
302
303 fn are_equal<'tcx>(cx: &LateContext<'tcx>, middle_ty: Ty<'_>, hir_ty: &rustc_hir::Ty<'_>) -> bool {
304     if_chain! {
305         if let ty::Adt(adt_def, _) = middle_ty.kind();
306         if let Some(local_did) = adt_def.did().as_local();
307         let item = cx.tcx.hir().expect_item(local_did);
308         let middle_ty_id = item.def_id.to_def_id();
309         if let TyKind::Path(QPath::Resolved(_, path)) = hir_ty.kind;
310         if let Res::Def(_, hir_ty_id) = path.res;
311
312         then {
313             hir_ty_id == middle_ty_id
314         }
315         else {
316             false
317         }
318     }
319 }