]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/eq_op.rs
Rollup merge of #92586 - esp-rs:bugfix/allocation-alignment-espidf, r=yaahc
[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::macros::{find_assert_eq_args, first_node_macro_backtrace};
3 use clippy_utils::source::snippet;
4 use clippy_utils::ty::{implements_trait, is_copy};
5 use clippy_utils::{ast_utils::is_useless_with_eq_exprs, eq_expr_value, is_in_test_function};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BinOpKind, BorrowKind, Expr, ExprKind};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11
12 declare_clippy_lint! {
13     /// ### What it does
14     /// Checks for equal operands to comparison, logical and
15     /// bitwise, difference and division binary operators (`==`, `>`, etc., `&&`,
16     /// `||`, `&`, `|`, `^`, `-` and `/`).
17     ///
18     /// ### Why is this bad?
19     /// This is usually just a typo or a copy and paste error.
20     ///
21     /// ### Known problems
22     /// False negatives: We had some false positives regarding
23     /// calls (notably [racer](https://github.com/phildawes/racer) had one instance
24     /// of `x.pop() && x.pop()`), so we removed matching any function or method
25     /// calls. We may introduce a list of known pure functions in the future.
26     ///
27     /// ### Example
28     /// ```rust
29     /// # let x = 1;
30     /// if x + 1 == x + 1 {}
31     /// ```
32     /// or
33     /// ```rust
34     /// # let a = 3;
35     /// # let b = 4;
36     /// assert_eq!(a, a);
37     /// ```
38     #[clippy::version = "pre 1.29.0"]
39     pub EQ_OP,
40     correctness,
41     "equal operands on both sides of a comparison or bitwise combination (e.g., `x == x`)"
42 }
43
44 declare_clippy_lint! {
45     /// ### What it does
46     /// Checks for arguments to `==` which have their address
47     /// taken to satisfy a bound
48     /// and suggests to dereference the other argument instead
49     ///
50     /// ### Why is this bad?
51     /// It is more idiomatic to dereference the other argument.
52     ///
53     /// ### Known problems
54     /// None
55     ///
56     /// ### Example
57     /// ```ignore
58     /// // Bad
59     /// &x == y
60     ///
61     /// // Good
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     #[allow(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                 #[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 }