]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/eq_op.rs
Rollup merge of #96142 - cjgillot:no-crate-def-index, r=petrochenkov
[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     #[allow(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                 #[allow(clippy::match_same_arms)]
142                 match (&left.kind, &right.kind) {
143                     // do not suggest to dereference literals
144                     (&ExprKind::Lit(..), _) | (_, &ExprKind::Lit(..)) => {},
145                     // &foo == &bar
146                     (&ExprKind::AddrOf(BorrowKind::Ref, _, l), &ExprKind::AddrOf(BorrowKind::Ref, _, r)) => {
147                         let lty = cx.typeck_results().expr_ty(l);
148                         let rty = cx.typeck_results().expr_ty(r);
149                         let lcpy = is_copy(cx, lty);
150                         let rcpy = is_copy(cx, rty);
151                         if let Some((self_ty, other_ty)) = in_impl(cx, e, trait_id) {
152                             if (are_equal(cx, rty, self_ty) && are_equal(cx, lty, other_ty))
153                                 || (are_equal(cx, rty, other_ty) && are_equal(cx, lty, self_ty))
154                             {
155                                 return; // Don't lint
156                             }
157                         }
158                         // either operator autorefs or both args are copyable
159                         if (requires_ref || (lcpy && rcpy)) && implements_trait(cx, lty, trait_id, &[rty.into()]) {
160                             span_lint_and_then(
161                                 cx,
162                                 OP_REF,
163                                 e.span,
164                                 "needlessly taken reference of both operands",
165                                 |diag| {
166                                     let lsnip = snippet(cx, l.span, "...").to_string();
167                                     let rsnip = snippet(cx, r.span, "...").to_string();
168                                     multispan_sugg(
169                                         diag,
170                                         "use the values directly",
171                                         vec![(left.span, lsnip), (right.span, rsnip)],
172                                     );
173                                 },
174                             );
175                         } else if lcpy
176                             && !rcpy
177                             && implements_trait(cx, lty, trait_id, &[cx.typeck_results().expr_ty(right).into()])
178                         {
179                             span_lint_and_then(
180                                 cx,
181                                 OP_REF,
182                                 e.span,
183                                 "needlessly taken reference of left operand",
184                                 |diag| {
185                                     let lsnip = snippet(cx, l.span, "...").to_string();
186                                     diag.span_suggestion(
187                                         left.span,
188                                         "use the left value directly",
189                                         lsnip,
190                                         Applicability::MaybeIncorrect, // FIXME #2597
191                                     );
192                                 },
193                             );
194                         } else if !lcpy
195                             && rcpy
196                             && implements_trait(cx, cx.typeck_results().expr_ty(left), trait_id, &[rty.into()])
197                         {
198                             span_lint_and_then(
199                                 cx,
200                                 OP_REF,
201                                 e.span,
202                                 "needlessly taken reference of right operand",
203                                 |diag| {
204                                     let rsnip = snippet(cx, r.span, "...").to_string();
205                                     diag.span_suggestion(
206                                         right.span,
207                                         "use the right value directly",
208                                         rsnip,
209                                         Applicability::MaybeIncorrect, // FIXME #2597
210                                     );
211                                 },
212                             );
213                         }
214                     },
215                     // &foo == bar
216                     (&ExprKind::AddrOf(BorrowKind::Ref, _, l), _) => {
217                         let lty = cx.typeck_results().expr_ty(l);
218                         if let Some((self_ty, other_ty)) = in_impl(cx, e, trait_id) {
219                             let rty = cx.typeck_results().expr_ty(right);
220                             if (are_equal(cx, rty, self_ty) && are_equal(cx, lty, other_ty))
221                                 || (are_equal(cx, rty, other_ty) && are_equal(cx, lty, self_ty))
222                             {
223                                 return; // Don't lint
224                             }
225                         }
226                         let lcpy = is_copy(cx, lty);
227                         if (requires_ref || lcpy)
228                             && implements_trait(cx, lty, trait_id, &[cx.typeck_results().expr_ty(right).into()])
229                         {
230                             span_lint_and_then(
231                                 cx,
232                                 OP_REF,
233                                 e.span,
234                                 "needlessly taken reference of left operand",
235                                 |diag| {
236                                     let lsnip = snippet(cx, l.span, "...").to_string();
237                                     diag.span_suggestion(
238                                         left.span,
239                                         "use the left value directly",
240                                         lsnip,
241                                         Applicability::MaybeIncorrect, // FIXME #2597
242                                     );
243                                 },
244                             );
245                         }
246                     },
247                     // foo == &bar
248                     (_, &ExprKind::AddrOf(BorrowKind::Ref, _, r)) => {
249                         let rty = cx.typeck_results().expr_ty(r);
250                         if let Some((self_ty, other_ty)) = in_impl(cx, e, trait_id) {
251                             let lty = cx.typeck_results().expr_ty(left);
252                             if (are_equal(cx, rty, self_ty) && are_equal(cx, lty, other_ty))
253                                 || (are_equal(cx, rty, other_ty) && are_equal(cx, lty, self_ty))
254                             {
255                                 return; // Don't lint
256                             }
257                         }
258                         let rcpy = is_copy(cx, rty);
259                         if (requires_ref || rcpy)
260                             && implements_trait(cx, cx.typeck_results().expr_ty(left), trait_id, &[rty.into()])
261                         {
262                             span_lint_and_then(cx, OP_REF, e.span, "taken reference of right operand", |diag| {
263                                 let rsnip = snippet(cx, r.span, "...").to_string();
264                                 diag.span_suggestion(
265                                     right.span,
266                                     "use the right value directly",
267                                     rsnip,
268                                     Applicability::MaybeIncorrect, // FIXME #2597
269                                 );
270                             });
271                         }
272                     },
273                     _ => {},
274                 }
275             }
276         }
277     }
278 }
279
280 fn in_impl<'tcx>(
281     cx: &LateContext<'tcx>,
282     e: &'tcx Expr<'_>,
283     bin_op: DefId,
284 ) -> Option<(&'tcx rustc_hir::Ty<'tcx>, &'tcx rustc_hir::Ty<'tcx>)> {
285     if_chain! {
286         if let Some(block) = get_enclosing_block(cx, e.hir_id);
287         if let Some(impl_def_id) = cx.tcx.impl_of_method(block.hir_id.owner.to_def_id());
288         let item = cx.tcx.hir().expect_item(impl_def_id.expect_local());
289         if let ItemKind::Impl(item) = &item.kind;
290         if let Some(of_trait) = &item.of_trait;
291         if let Some(seg) = of_trait.path.segments.last();
292         if let Some(Res::Def(_, trait_id)) = seg.res;
293         if trait_id == bin_op;
294         if let Some(generic_args) = seg.args;
295         if let Some(GenericArg::Type(other_ty)) = generic_args.args.last();
296
297         then {
298             Some((item.self_ty, other_ty))
299         }
300         else {
301             None
302         }
303     }
304 }
305
306 fn are_equal<'tcx>(cx: &LateContext<'tcx>, middle_ty: Ty<'_>, hir_ty: &rustc_hir::Ty<'_>) -> bool {
307     if_chain! {
308         if let ty::Adt(adt_def, _) = middle_ty.kind();
309         if let Some(local_did) = adt_def.did().as_local();
310         let item = cx.tcx.hir().expect_item(local_did);
311         let middle_ty_id = item.def_id.to_def_id();
312         if let TyKind::Path(QPath::Resolved(_, path)) = hir_ty.kind;
313         if let Res::Def(_, hir_ty_id) = path.res;
314
315         then {
316             hir_ty_id == middle_ty_id
317         }
318         else {
319             false
320         }
321     }
322 }