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