1 use if_chain::if_chain;
3 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::{declare_tool_lint, lint_array};
6 use rustc_errors::Applicability;
9 get_trait_def_id, implements_trait, snippet_opt, span_lint_and_then, trait_ref_of_method, SpanlessEq,
11 use crate::utils::{higher, sugg};
13 declare_clippy_lint! {
14 /// **What it does:** Checks for `a = a op b` or `a = b commutative_op a`
17 /// **Why is this bad?** These can be written as the shorter `a op= b`.
19 /// **Known problems:** While forbidden by the spec, `OpAssign` traits may have
20 /// implementations that differ from the regular `Op` impl.
28 pub ASSIGN_OP_PATTERN,
30 "assigning the result of an operation on a variable to that same variable"
33 declare_clippy_lint! {
34 /// **What it does:** Checks for `a op= a op b` or `a op= b op a` patterns.
36 /// **Why is this bad?** Most likely these are bugs where one meant to write `a
39 /// **Known problems:** Clippy cannot know for sure if `a op= a op b` should have
40 /// been `a = a op a op b` or `a = a op b`/`a op= b`. Therefore, it suggests both.
41 /// If `a op= a op b` is really the correct behaviour it should be
42 /// written as `a = a op a op b` as it's less confusing.
50 pub MISREFACTORED_ASSIGN_OP,
52 "having a variable on both sides of an assign op"
55 #[derive(Copy, Clone, Default)]
58 impl LintPass for AssignOps {
59 fn get_lints(&self) -> LintArray {
60 lint_array!(ASSIGN_OP_PATTERN, MISREFACTORED_ASSIGN_OP)
63 fn name(&self) -> &'static str {
68 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
69 #[allow(clippy::too_many_lines)]
70 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
72 hir::ExprKind::AssignOp(op, lhs, rhs) => {
73 if let hir::ExprKind::Binary(binop, l, r) = &rhs.node {
74 if op.node != binop.node {
78 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, l) {
79 lint_misrefactored_assign_op(cx, expr, *op, rhs, lhs, r);
81 // lhs op= l commutative_op r
82 if is_commutative(op.node) && SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, r) {
83 lint_misrefactored_assign_op(cx, expr, *op, rhs, lhs, l);
87 hir::ExprKind::Assign(assignee, e) => {
88 if let hir::ExprKind::Binary(op, l, r) = &e.node {
89 #[allow(clippy::cognitive_complexity)]
90 let lint = |assignee: &hir::Expr, rhs: &hir::Expr| {
91 let ty = cx.tables.expr_ty(assignee);
92 let rty = cx.tables.expr_ty(rhs);
98 $($trait_name:ident),+) => {
100 $(hir::BinOpKind::$trait_name => {
101 let [krate, module] = crate::utils::paths::OPS_MODULE;
102 let path = [krate, module, concat!(stringify!($trait_name), "Assign")];
103 let trait_id = if let Some(trait_id) = get_trait_def_id($cx, &path) {
106 return; // useless if the trait doesn't exist
108 // check that we are not inside an `impl AssignOp` of this exact operation
109 let parent_fn = cx.tcx.hir().get_parent_item(e.hir_id);
111 if let Some(trait_ref) = trait_ref_of_method(cx, parent_fn);
112 if trait_ref.path.def.def_id() == trait_id;
115 implements_trait($cx, $ty, trait_id, &[$rty])
143 "manual implementation of an assign operation",
145 if let (Some(snip_a), Some(snip_r)) =
146 (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span))
151 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
152 Applicability::MachineApplicable,
160 let mut visitor = ExprVisitor {
166 walk_expr(&mut visitor, e);
168 if visitor.counter == 1 {
170 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, l) {
173 // a = b commutative_op a
174 // Limited to primitive type as these ops are know to be commutative
175 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r)
176 && cx.tables.expr_ty(assignee).is_primitive_ty()
180 | hir::BinOpKind::Mul
181 | hir::BinOpKind::And
183 | hir::BinOpKind::BitXor
184 | hir::BinOpKind::BitAnd
185 | hir::BinOpKind::BitOr => {
199 fn lint_misrefactored_assign_op(
200 cx: &LateContext<'_, '_>,
204 assignee: &hir::Expr,
205 rhs_other: &hir::Expr,
209 MISREFACTORED_ASSIGN_OP,
211 "variable appears on both sides of an assignment operation",
213 if let (Some(snip_a), Some(snip_r)) = (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs_other.span)) {
214 let a = &sugg::Sugg::hir(cx, assignee, "..");
215 let r = &sugg::Sugg::hir(cx, rhs, "..");
216 let long = format!("{} = {}", snip_a, sugg::make_binop(higher::binop(op.node), a, r));
220 "Did you mean {} = {} {} {} or {}? Consider replacing it with",
227 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
228 Applicability::MachineApplicable,
234 Applicability::MachineApplicable, // snippet
241 fn is_commutative(op: hir::BinOpKind) -> bool {
242 use rustc::hir::BinOpKind::*;
244 Add | Mul | And | Or | BitXor | BitAnd | BitOr | Eq | Ne => true,
245 Sub | Div | Rem | Shl | Shr | Lt | Le | Ge | Gt => false,
249 struct ExprVisitor<'a, 'tcx: 'a> {
250 assignee: &'a hir::Expr,
252 cx: &'a LateContext<'a, 'tcx>,
255 impl<'a, 'tcx: 'a> Visitor<'tcx> for ExprVisitor<'a, 'tcx> {
256 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
257 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(self.assignee, expr) {
261 walk_expr(self, expr);
263 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
264 NestedVisitorMap::None