1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::source::snippet_opt;
3 use clippy_utils::ty::implements_trait;
4 use clippy_utils::{binop_traits, sugg};
5 use clippy_utils::{eq_expr_value, trait_ref_of_method};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
9 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::hir::map::Map;
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 declare_clippy_lint! {
15 /// **What it does:** Checks for `a = a op b` or `a = b commutative_op a`
18 /// **Why is this bad?** These can be written as the shorter `a op= b`.
20 /// **Known problems:** While forbidden by the spec, `OpAssign` traits may have
21 /// implementations that differ from the regular `Op` impl.
34 pub ASSIGN_OP_PATTERN,
36 "assigning the result of an operation on a variable to that same variable"
39 declare_clippy_lint! {
40 /// **What it does:** Checks for `a op= a op b` or `a op= b op a` patterns.
42 /// **Why is this bad?** Most likely these are bugs where one meant to write `a
45 /// **Known problems:** Clippy cannot know for sure if `a op= a op b` should have
46 /// been `a = a op a op b` or `a = a op b`/`a op= b`. Therefore, it suggests both.
47 /// If `a op= a op b` is really the correct behaviour it should be
48 /// written as `a = a op a op b` as it's less confusing.
57 pub MISREFACTORED_ASSIGN_OP,
59 "having a variable on both sides of an assign op"
62 declare_lint_pass!(AssignOps => [ASSIGN_OP_PATTERN, MISREFACTORED_ASSIGN_OP]);
64 impl<'tcx> LateLintPass<'tcx> for AssignOps {
65 #[allow(clippy::too_many_lines)]
66 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
68 hir::ExprKind::AssignOp(op, lhs, rhs) => {
69 if let hir::ExprKind::Binary(binop, l, r) = &rhs.kind {
70 if op.node != binop.node {
74 if eq_expr_value(cx, lhs, l) {
75 lint_misrefactored_assign_op(cx, expr, *op, rhs, lhs, r);
77 // lhs op= l commutative_op r
78 if is_commutative(op.node) && eq_expr_value(cx, lhs, r) {
79 lint_misrefactored_assign_op(cx, expr, *op, rhs, lhs, l);
83 hir::ExprKind::Assign(assignee, e, _) => {
84 if let hir::ExprKind::Binary(op, l, r) = &e.kind {
85 let lint = |assignee: &hir::Expr<'_>, rhs: &hir::Expr<'_>| {
86 let ty = cx.typeck_results().expr_ty(assignee);
87 let rty = cx.typeck_results().expr_ty(rhs);
89 if let Some((_, lang_item)) = binop_traits(op.node);
90 if let Ok(trait_id) = cx.tcx.lang_items().require(lang_item);
91 let parent_fn = cx.tcx.hir().get_parent_item(e.hir_id);
92 if trait_ref_of_method(cx, parent_fn)
93 .map_or(true, |t| t.path.res.def_id() != trait_id);
94 if implements_trait(cx, ty, trait_id, &[rty.into()]);
100 "manual implementation of an assign operation",
102 if let (Some(snip_a), Some(snip_r)) =
103 (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span))
105 diag.span_suggestion(
108 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
109 Applicability::MachineApplicable,
118 let mut visitor = ExprVisitor {
124 walk_expr(&mut visitor, e);
126 if visitor.counter == 1 {
128 if eq_expr_value(cx, assignee, l) {
131 // a = b commutative_op a
132 // Limited to primitive type as these ops are know to be commutative
133 if eq_expr_value(cx, assignee, r) && cx.typeck_results().expr_ty(assignee).is_primitive_ty() {
136 | hir::BinOpKind::Mul
137 | hir::BinOpKind::And
139 | hir::BinOpKind::BitXor
140 | hir::BinOpKind::BitAnd
141 | hir::BinOpKind::BitOr => {
155 fn lint_misrefactored_assign_op(
156 cx: &LateContext<'_>,
157 expr: &hir::Expr<'_>,
160 assignee: &hir::Expr<'_>,
161 rhs_other: &hir::Expr<'_>,
165 MISREFACTORED_ASSIGN_OP,
167 "variable appears on both sides of an assignment operation",
169 if let (Some(snip_a), Some(snip_r)) = (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs_other.span)) {
170 let a = &sugg::Sugg::hir(cx, assignee, "..");
171 let r = &sugg::Sugg::hir(cx, rhs, "..");
172 let long = format!("{} = {}", snip_a, sugg::make_binop(op.node.into(), a, r));
173 diag.span_suggestion(
176 "did you mean `{} = {} {} {}` or `{}`? Consider replacing it with",
183 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
184 Applicability::MaybeIncorrect,
186 diag.span_suggestion(
190 Applicability::MaybeIncorrect, // snippet
198 fn is_commutative(op: hir::BinOpKind) -> bool {
199 use rustc_hir::BinOpKind::{
200 Add, And, BitAnd, BitOr, BitXor, Div, Eq, Ge, Gt, Le, Lt, Mul, Ne, Or, Rem, Shl, Shr, Sub,
203 Add | Mul | And | Or | BitXor | BitAnd | BitOr | Eq | Ne => true,
204 Sub | Div | Rem | Shl | Shr | Lt | Le | Ge | Gt => false,
208 struct ExprVisitor<'a, 'tcx> {
209 assignee: &'a hir::Expr<'a>,
211 cx: &'a LateContext<'tcx>,
214 impl<'a, 'tcx> Visitor<'tcx> for ExprVisitor<'a, 'tcx> {
215 type Map = Map<'tcx>;
217 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
218 if eq_expr_value(self.cx, self.assignee, expr) {
222 walk_expr(self, expr);
224 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
225 NestedVisitorMap::None