]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/eq_op.rs
Rollup merge of #97415 - cjgillot:is-late-bound-solo, r=estebank
[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::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     /// ```rust
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     /// ### Known problems
56     /// None
57     ///
58     /// ### Example
59     /// ```ignore
60     /// // Bad
61     /// &x == y
62     ///
63     /// // Good
64     /// x == *y
65     /// ```
66     #[clippy::version = "pre 1.29.0"]
67     pub OP_REF,
68     style,
69     "taking a reference to satisfy the type constraints on `==`"
70 }
71
72 declare_lint_pass!(EqOp => [EQ_OP, OP_REF]);
73
74 impl<'tcx> LateLintPass<'tcx> for EqOp {
75     #[expect(clippy::similar_names, clippy::too_many_lines)]
76     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
77         if_chain! {
78             if let Some((macro_call, macro_name)) = first_node_macro_backtrace(cx, e).find_map(|macro_call| {
79                 let name = cx.tcx.item_name(macro_call.def_id);
80                 matches!(name.as_str(), "assert_eq" | "assert_ne" | "debug_assert_eq" | "debug_assert_ne")
81                     .then(|| (macro_call, name))
82             });
83             if let Some((lhs, rhs, _)) = find_assert_eq_args(cx, e, macro_call.expn);
84             if eq_expr_value(cx, lhs, rhs);
85             if macro_call.is_local();
86             if !is_in_test_function(cx.tcx, e.hir_id);
87             then {
88                 span_lint(
89                     cx,
90                     EQ_OP,
91                     lhs.span.to(rhs.span),
92                     &format!("identical args used in this `{}!` macro call", macro_name),
93                 );
94             }
95         }
96         if let ExprKind::Binary(op, left, right) = e.kind {
97             if e.span.from_expansion() {
98                 return;
99             }
100             let macro_with_not_op = |expr_kind: &ExprKind<'_>| {
101                 if let ExprKind::Unary(_, expr) = *expr_kind {
102                     expr.span.from_expansion()
103                 } else {
104                     false
105                 }
106             };
107             if macro_with_not_op(&left.kind) || macro_with_not_op(&right.kind) {
108                 return;
109             }
110             if is_useless_with_eq_exprs(op.node.into())
111                 && eq_expr_value(cx, left, right)
112                 && !is_in_test_function(cx.tcx, e.hir_id)
113             {
114                 span_lint(
115                     cx,
116                     EQ_OP,
117                     e.span,
118                     &format!("equal expressions as operands to `{}`", op.node.as_str()),
119                 );
120                 return;
121             }
122             let (trait_id, requires_ref) = match op.node {
123                 BinOpKind::Add => (cx.tcx.lang_items().add_trait(), false),
124                 BinOpKind::Sub => (cx.tcx.lang_items().sub_trait(), false),
125                 BinOpKind::Mul => (cx.tcx.lang_items().mul_trait(), false),
126                 BinOpKind::Div => (cx.tcx.lang_items().div_trait(), false),
127                 BinOpKind::Rem => (cx.tcx.lang_items().rem_trait(), false),
128                 // don't lint short circuiting ops
129                 BinOpKind::And | BinOpKind::Or => return,
130                 BinOpKind::BitXor => (cx.tcx.lang_items().bitxor_trait(), false),
131                 BinOpKind::BitAnd => (cx.tcx.lang_items().bitand_trait(), false),
132                 BinOpKind::BitOr => (cx.tcx.lang_items().bitor_trait(), false),
133                 BinOpKind::Shl => (cx.tcx.lang_items().shl_trait(), false),
134                 BinOpKind::Shr => (cx.tcx.lang_items().shr_trait(), false),
135                 BinOpKind::Ne | BinOpKind::Eq => (cx.tcx.lang_items().eq_trait(), true),
136                 BinOpKind::Lt | BinOpKind::Le | BinOpKind::Ge | BinOpKind::Gt => {
137                     (cx.tcx.lang_items().partial_ord_trait(), true)
138                 },
139             };
140             if let Some(trait_id) = trait_id {
141                 match (&left.kind, &right.kind) {
142                     // do not suggest to dereference literals
143                     (&ExprKind::Lit(..), _) | (_, &ExprKind::Lit(..)) => {},
144                     // &foo == &bar
145                     (&ExprKind::AddrOf(BorrowKind::Ref, _, l), &ExprKind::AddrOf(BorrowKind::Ref, _, r)) => {
146                         let lty = cx.typeck_results().expr_ty(l);
147                         let rty = cx.typeck_results().expr_ty(r);
148                         let lcpy = is_copy(cx, lty);
149                         let rcpy = is_copy(cx, rty);
150                         if let Some((self_ty, other_ty)) = in_impl(cx, e, trait_id) {
151                             if (are_equal(cx, rty, self_ty) && are_equal(cx, lty, other_ty))
152                                 || (are_equal(cx, rty, other_ty) && are_equal(cx, lty, self_ty))
153                             {
154                                 return; // Don't lint
155                             }
156                         }
157                         // either operator autorefs or both args are copyable
158                         if (requires_ref || (lcpy && rcpy)) && implements_trait(cx, lty, trait_id, &[rty.into()]) {
159                             span_lint_and_then(
160                                 cx,
161                                 OP_REF,
162                                 e.span,
163                                 "needlessly taken reference of both operands",
164                                 |diag| {
165                                     let lsnip = snippet(cx, l.span, "...").to_string();
166                                     let rsnip = snippet(cx, r.span, "...").to_string();
167                                     multispan_sugg(
168                                         diag,
169                                         "use the values directly",
170                                         vec![(left.span, lsnip), (right.span, rsnip)],
171                                     );
172                                 },
173                             );
174                         } else if lcpy
175                             && !rcpy
176                             && implements_trait(cx, lty, trait_id, &[cx.typeck_results().expr_ty(right).into()])
177                         {
178                             span_lint_and_then(
179                                 cx,
180                                 OP_REF,
181                                 e.span,
182                                 "needlessly taken reference of left operand",
183                                 |diag| {
184                                     let lsnip = snippet(cx, l.span, "...").to_string();
185                                     diag.span_suggestion(
186                                         left.span,
187                                         "use the left value directly",
188                                         lsnip,
189                                         Applicability::MaybeIncorrect, // FIXME #2597
190                                     );
191                                 },
192                             );
193                         } else if !lcpy
194                             && rcpy
195                             && implements_trait(cx, cx.typeck_results().expr_ty(left), trait_id, &[rty.into()])
196                         {
197                             span_lint_and_then(
198                                 cx,
199                                 OP_REF,
200                                 e.span,
201                                 "needlessly taken reference of right operand",
202                                 |diag| {
203                                     let rsnip = snippet(cx, r.span, "...").to_string();
204                                     diag.span_suggestion(
205                                         right.span,
206                                         "use the right value directly",
207                                         rsnip,
208                                         Applicability::MaybeIncorrect, // FIXME #2597
209                                     );
210                                 },
211                             );
212                         }
213                     },
214                     // &foo == bar
215                     (&ExprKind::AddrOf(BorrowKind::Ref, _, l), _) => {
216                         let lty = cx.typeck_results().expr_ty(l);
217                         if let Some((self_ty, other_ty)) = in_impl(cx, e, trait_id) {
218                             let rty = cx.typeck_results().expr_ty(right);
219                             if (are_equal(cx, rty, self_ty) && are_equal(cx, lty, other_ty))
220                                 || (are_equal(cx, rty, other_ty) && are_equal(cx, lty, self_ty))
221                             {
222                                 return; // Don't lint
223                             }
224                         }
225                         let lcpy = is_copy(cx, lty);
226                         if (requires_ref || lcpy)
227                             && implements_trait(cx, lty, trait_id, &[cx.typeck_results().expr_ty(right).into()])
228                         {
229                             span_lint_and_then(
230                                 cx,
231                                 OP_REF,
232                                 e.span,
233                                 "needlessly taken reference of left operand",
234                                 |diag| {
235                                     let lsnip = snippet(cx, l.span, "...").to_string();
236                                     diag.span_suggestion(
237                                         left.span,
238                                         "use the left value directly",
239                                         lsnip,
240                                         Applicability::MaybeIncorrect, // FIXME #2597
241                                     );
242                                 },
243                             );
244                         }
245                     },
246                     // foo == &bar
247                     (_, &ExprKind::AddrOf(BorrowKind::Ref, _, r)) => {
248                         let rty = cx.typeck_results().expr_ty(r);
249                         if let Some((self_ty, other_ty)) = in_impl(cx, e, trait_id) {
250                             let lty = cx.typeck_results().expr_ty(left);
251                             if (are_equal(cx, rty, self_ty) && are_equal(cx, lty, other_ty))
252                                 || (are_equal(cx, rty, other_ty) && are_equal(cx, lty, self_ty))
253                             {
254                                 return; // Don't lint
255                             }
256                         }
257                         let rcpy = is_copy(cx, rty);
258                         if (requires_ref || rcpy)
259                             && implements_trait(cx, cx.typeck_results().expr_ty(left), trait_id, &[rty.into()])
260                         {
261                             span_lint_and_then(cx, OP_REF, e.span, "taken reference of right operand", |diag| {
262                                 let rsnip = snippet(cx, r.span, "...").to_string();
263                                 diag.span_suggestion(
264                                     right.span,
265                                     "use the right value directly",
266                                     rsnip,
267                                     Applicability::MaybeIncorrect, // FIXME #2597
268                                 );
269                             });
270                         }
271                     },
272                     _ => {},
273                 }
274             }
275         }
276     }
277 }
278
279 fn in_impl<'tcx>(
280     cx: &LateContext<'tcx>,
281     e: &'tcx Expr<'_>,
282     bin_op: DefId,
283 ) -> Option<(&'tcx rustc_hir::Ty<'tcx>, &'tcx rustc_hir::Ty<'tcx>)> {
284     if_chain! {
285         if let Some(block) = get_enclosing_block(cx, e.hir_id);
286         if let Some(impl_def_id) = cx.tcx.impl_of_method(block.hir_id.owner.to_def_id());
287         let item = cx.tcx.hir().expect_item(impl_def_id.expect_local());
288         if let ItemKind::Impl(item) = &item.kind;
289         if let Some(of_trait) = &item.of_trait;
290         if let Some(seg) = of_trait.path.segments.last();
291         if let Some(Res::Def(_, trait_id)) = seg.res;
292         if trait_id == bin_op;
293         if let Some(generic_args) = seg.args;
294         if let Some(GenericArg::Type(other_ty)) = generic_args.args.last();
295
296         then {
297             Some((item.self_ty, other_ty))
298         }
299         else {
300             None
301         }
302     }
303 }
304
305 fn are_equal<'tcx>(cx: &LateContext<'tcx>, middle_ty: Ty<'_>, hir_ty: &rustc_hir::Ty<'_>) -> bool {
306     if_chain! {
307         if let ty::Adt(adt_def, _) = middle_ty.kind();
308         if let Some(local_did) = adt_def.did().as_local();
309         let item = cx.tcx.hir().expect_item(local_did);
310         let middle_ty_id = item.def_id.to_def_id();
311         if let TyKind::Path(QPath::Resolved(_, path)) = hir_ty.kind;
312         if let Res::Def(_, hir_ty_id) = path.res;
313
314         then {
315             hir_ty_id == middle_ty_id
316         }
317         else {
318             false
319         }
320     }
321 }