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;
10 def::Res, def_id::DefId, BinOpKind, BorrowKind, Expr, ExprKind, GenericArg, ItemKind, QPath, Ty, TyKind,
12 use rustc_lint::{LateContext, LateLintPass};
13 use rustc_middle::ty::{self, TyS};
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
16 declare_clippy_lint! {
18 /// Checks for equal operands to comparison, logical and
19 /// bitwise, difference and division binary operators (`==`, `>`, etc., `&&`,
20 /// `||`, `&`, `|`, `^`, `-` and `/`).
22 /// ### Why is this bad?
23 /// This is usually just a typo or a copy and paste error.
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.
34 /// if x + 1 == x + 1 {}
42 #[clippy::version = "pre 1.29.0"]
45 "equal operands on both sides of a comparison or bitwise combination (e.g., `x == x`)"
48 declare_clippy_lint! {
50 /// Checks for arguments to `==` which have their address
51 /// taken to satisfy a bound
52 /// and suggests to dereference the other argument instead
54 /// ### Why is this bad?
55 /// It is more idiomatic to dereference the other argument.
57 /// ### Known problems
68 #[clippy::version = "pre 1.29.0"]
71 "taking a reference to satisfy the type constraints on `==`"
74 declare_lint_pass!(EqOp => [EQ_OP, OP_REF]);
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<'_>) {
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))
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);
93 lhs.span.to(rhs.span),
94 &format!("identical args used in this `{}!` macro call", macro_name),
98 if let ExprKind::Binary(op, left, right) = e.kind {
99 if e.span.from_expansion() {
102 let macro_with_not_op = |expr_kind: &ExprKind<'_>| {
103 if let ExprKind::Unary(_, expr) = *expr_kind {
104 expr.span.from_expansion()
109 if macro_with_not_op(&left.kind) || macro_with_not_op(&right.kind) {
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)
120 &format!("equal expressions as operands to `{}`", op.node.as_str()),
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)
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(..)) => {},
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))
157 return; // Don't lint
160 // either operator autorefs or both args are copyable
161 if (requires_ref || (lcpy && rcpy)) && implements_trait(cx, lty, trait_id, &[rty.into()]) {
166 "needlessly taken reference of both operands",
168 let lsnip = snippet(cx, l.span, "...").to_string();
169 let rsnip = snippet(cx, r.span, "...").to_string();
172 "use the values directly",
173 vec![(left.span, lsnip), (right.span, rsnip)],
179 && implements_trait(cx, lty, trait_id, &[cx.typeck_results().expr_ty(right).into()])
185 "needlessly taken reference of left operand",
187 let lsnip = snippet(cx, l.span, "...").to_string();
188 diag.span_suggestion(
190 "use the left value directly",
192 Applicability::MaybeIncorrect, // FIXME #2597
198 && implements_trait(cx, cx.typeck_results().expr_ty(left), trait_id, &[rty.into()])
204 "needlessly taken reference of right operand",
206 let rsnip = snippet(cx, r.span, "...").to_string();
207 diag.span_suggestion(
209 "use the right value directly",
211 Applicability::MaybeIncorrect, // FIXME #2597
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))
225 return; // Don't lint
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()])
236 "needlessly taken reference of left operand",
238 let lsnip = snippet(cx, l.span, "...").to_string();
239 diag.span_suggestion(
241 "use the left value directly",
243 Applicability::MaybeIncorrect, // FIXME #2597
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))
257 return; // Don't lint
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()])
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(
268 "use the right value directly",
270 Applicability::MaybeIncorrect, // FIXME #2597
282 fn in_impl<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, bin_op: DefId) -> Option<(&'tcx Ty<'tcx>, &'tcx Ty<'tcx>)> {
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();
296 Some((item.self_ty, other_ty))
304 fn are_equal<'tcx>(cx: &LateContext<'tcx>, middle_ty: &TyS<'_>, hir_ty: &Ty<'_>) -> bool {
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;
314 hir_ty_id == middle_ty_id