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::{eq_expr_value, get_trait_def_id, trait_ref_of_method};
5 use clippy_utils::{higher, paths, sugg};
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);
93 $($trait_name:ident),+) => {
95 $(hir::BinOpKind::$trait_name => {
96 let [krate, module] = paths::OPS_MODULE;
97 let path: [&str; 3] = [krate, module, concat!(stringify!($trait_name), "Assign")];
98 let trait_id = if let Some(trait_id) = get_trait_def_id($cx, &path) {
101 return; // useless if the trait doesn't exist
103 // check that we are not inside an `impl AssignOp` of this exact operation
104 let parent_fn = cx.tcx.hir().get_parent_item(e.hir_id);
106 if let Some(trait_ref) = trait_ref_of_method(cx, parent_fn);
107 if trait_ref.path.res.def_id() == trait_id;
110 implements_trait($cx, $ty, trait_id, &[$rty])
138 "manual implementation of an assign operation",
140 if let (Some(snip_a), Some(snip_r)) =
141 (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span))
143 diag.span_suggestion(
146 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
147 Applicability::MachineApplicable,
155 let mut visitor = ExprVisitor {
161 walk_expr(&mut visitor, e);
163 if visitor.counter == 1 {
165 if eq_expr_value(cx, assignee, l) {
168 // a = b commutative_op a
169 // Limited to primitive type as these ops are know to be commutative
170 if eq_expr_value(cx, assignee, r) && cx.typeck_results().expr_ty(assignee).is_primitive_ty() {
173 | hir::BinOpKind::Mul
174 | hir::BinOpKind::And
176 | hir::BinOpKind::BitXor
177 | hir::BinOpKind::BitAnd
178 | hir::BinOpKind::BitOr => {
192 fn lint_misrefactored_assign_op(
193 cx: &LateContext<'_>,
194 expr: &hir::Expr<'_>,
197 assignee: &hir::Expr<'_>,
198 rhs_other: &hir::Expr<'_>,
202 MISREFACTORED_ASSIGN_OP,
204 "variable appears on both sides of an assignment operation",
206 if let (Some(snip_a), Some(snip_r)) = (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs_other.span)) {
207 let a = &sugg::Sugg::hir(cx, assignee, "..");
208 let r = &sugg::Sugg::hir(cx, rhs, "..");
209 let long = format!("{} = {}", snip_a, sugg::make_binop(higher::binop(op.node), a, r));
210 diag.span_suggestion(
213 "did you mean `{} = {} {} {}` or `{}`? Consider replacing it with",
220 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
221 Applicability::MaybeIncorrect,
223 diag.span_suggestion(
227 Applicability::MaybeIncorrect, // snippet
235 fn is_commutative(op: hir::BinOpKind) -> bool {
236 use rustc_hir::BinOpKind::{
237 Add, And, BitAnd, BitOr, BitXor, Div, Eq, Ge, Gt, Le, Lt, Mul, Ne, Or, Rem, Shl, Shr, Sub,
240 Add | Mul | And | Or | BitXor | BitAnd | BitOr | Eq | Ne => true,
241 Sub | Div | Rem | Shl | Shr | Lt | Le | Ge | Gt => false,
245 struct ExprVisitor<'a, 'tcx> {
246 assignee: &'a hir::Expr<'a>,
248 cx: &'a LateContext<'tcx>,
251 impl<'a, 'tcx> Visitor<'tcx> for ExprVisitor<'a, 'tcx> {
252 type Map = Map<'tcx>;
254 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
255 if eq_expr_value(self.cx, self.assignee, expr) {
259 walk_expr(self, expr);
261 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
262 NestedVisitorMap::None