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.
55 /// ### Known problems
66 #[clippy::version = "pre 1.29.0"]
69 "taking a reference to satisfy the type constraints on `==`"
72 declare_lint_pass!(EqOp => [EQ_OP, OP_REF]);
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<'_>) {
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))
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);
91 lhs.span.to(rhs.span),
92 &format!("identical args used in this `{}!` macro call", macro_name),
96 if let ExprKind::Binary(op, left, right) = e.kind {
97 if e.span.from_expansion() {
100 let macro_with_not_op = |expr_kind: &ExprKind<'_>| {
101 if let ExprKind::Unary(_, expr) = *expr_kind {
102 expr.span.from_expansion()
107 if macro_with_not_op(&left.kind) || macro_with_not_op(&right.kind) {
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)
118 &format!("equal expressions as operands to `{}`", op.node.as_str()),
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)
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(..)) => {},
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))
155 return; // Don't lint
158 // either operator autorefs or both args are copyable
159 if (requires_ref || (lcpy && rcpy)) && implements_trait(cx, lty, trait_id, &[rty.into()]) {
164 "needlessly taken reference of both operands",
166 let lsnip = snippet(cx, l.span, "...").to_string();
167 let rsnip = snippet(cx, r.span, "...").to_string();
170 "use the values directly",
171 vec![(left.span, lsnip), (right.span, rsnip)],
177 && implements_trait(cx, lty, trait_id, &[cx.typeck_results().expr_ty(right).into()])
183 "needlessly taken reference of left operand",
185 let lsnip = snippet(cx, l.span, "...").to_string();
186 diag.span_suggestion(
188 "use the left value directly",
190 Applicability::MaybeIncorrect, // FIXME #2597
196 && implements_trait(cx, cx.typeck_results().expr_ty(left), trait_id, &[rty.into()])
202 "needlessly taken reference of right operand",
204 let rsnip = snippet(cx, r.span, "...").to_string();
205 diag.span_suggestion(
207 "use the right value directly",
209 Applicability::MaybeIncorrect, // FIXME #2597
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))
223 return; // Don't lint
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()])
234 "needlessly taken reference of left operand",
236 let lsnip = snippet(cx, l.span, "...").to_string();
237 diag.span_suggestion(
239 "use the left value directly",
241 Applicability::MaybeIncorrect, // FIXME #2597
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))
255 return; // Don't lint
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()])
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(
266 "use the right value directly",
268 Applicability::MaybeIncorrect, // FIXME #2597
281 cx: &LateContext<'tcx>,
284 ) -> Option<(&'tcx rustc_hir::Ty<'tcx>, &'tcx rustc_hir::Ty<'tcx>)> {
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();
298 Some((item.self_ty, other_ty))
306 fn are_equal<'tcx>(cx: &LateContext<'tcx>, middle_ty: Ty<'_>, hir_ty: &rustc_hir::Ty<'_>) -> bool {
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;
316 hir_ty_id == middle_ty_id