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};
14 declare_clippy_lint! {
16 /// Checks for equal operands to comparison, logical and
17 /// bitwise, difference and division binary operators (`==`, `>`, etc., `&&`,
18 /// `||`, `&`, `|`, `^`, `-` and `/`).
20 /// ### Why is this bad?
21 /// This is usually just a typo or a copy and paste error.
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.
32 /// if x + 1 == x + 1 {}
40 #[clippy::version = "pre 1.29.0"]
43 "equal operands on both sides of a comparison or bitwise combination (e.g., `x == x`)"
46 declare_clippy_lint! {
48 /// Checks for arguments to `==` which have their address
49 /// taken to satisfy a bound
50 /// and suggests to dereference the other argument instead
52 /// ### Why is this bad?
53 /// It is more idiomatic to dereference the other argument.
64 #[clippy::version = "pre 1.29.0"]
67 "taking a reference to satisfy the type constraints on `==`"
70 declare_lint_pass!(EqOp => [EQ_OP, OP_REF]);
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<'_>) {
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))
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);
89 lhs.span.to(rhs.span),
90 &format!("identical args used in this `{}!` macro call", macro_name),
94 if let ExprKind::Binary(op, left, right) = e.kind {
95 if e.span.from_expansion() {
98 let macro_with_not_op = |expr_kind: &ExprKind<'_>| {
99 if let ExprKind::Unary(_, expr) = *expr_kind {
100 expr.span.from_expansion()
105 if macro_with_not_op(&left.kind) || macro_with_not_op(&right.kind) {
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)
116 &format!("equal expressions as operands to `{}`", op.node.as_str()),
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)
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(..)) => {},
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))
152 return; // Don't lint
155 // either operator autorefs or both args are copyable
156 if (requires_ref || (lcpy && rcpy)) && implements_trait(cx, lty, trait_id, &[rty.into()]) {
161 "needlessly taken reference of both operands",
163 let lsnip = snippet(cx, l.span, "...").to_string();
164 let rsnip = snippet(cx, r.span, "...").to_string();
167 "use the values directly",
168 vec![(left.span, lsnip), (right.span, rsnip)],
174 && implements_trait(cx, lty, trait_id, &[cx.typeck_results().expr_ty(right).into()])
180 "needlessly taken reference of left operand",
182 let lsnip = snippet(cx, l.span, "...").to_string();
183 diag.span_suggestion(
185 "use the left value directly",
187 Applicability::MaybeIncorrect, // FIXME #2597
193 && implements_trait(cx, cx.typeck_results().expr_ty(left), trait_id, &[rty.into()])
199 "needlessly taken reference of right operand",
201 let rsnip = snippet(cx, r.span, "...").to_string();
202 diag.span_suggestion(
204 "use the right value directly",
206 Applicability::MaybeIncorrect, // FIXME #2597
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))
220 return; // Don't lint
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()])
231 "needlessly taken reference of left operand",
233 let lsnip = snippet(cx, l.span, "...").to_string();
234 diag.span_suggestion(
236 "use the left value directly",
238 Applicability::MaybeIncorrect, // FIXME #2597
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))
252 return; // Don't lint
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()])
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(
263 "use the right value directly",
265 Applicability::MaybeIncorrect, // FIXME #2597
278 cx: &LateContext<'tcx>,
281 ) -> Option<(&'tcx rustc_hir::Ty<'tcx>, &'tcx rustc_hir::Ty<'tcx>)> {
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();
295 Some((item.self_ty, other_ty))
303 fn are_equal<'tcx>(cx: &LateContext<'tcx>, middle_ty: Ty<'_>, hir_ty: &rustc_hir::Ty<'_>) -> bool {
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;
313 hir_ty_id == middle_ty_id