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.
29 pub ASSIGN_OP_PATTERN,
31 "assigning the result of an operation on a variable to that same variable"
34 declare_clippy_lint! {
35 /// **What it does:** Checks for `a op= a op b` or `a op= b op a` patterns.
37 /// **Why is this bad?** Most likely these are bugs where one meant to write `a
40 /// **Known problems:** Clippy cannot know for sure if `a op= a op b` should have
41 /// been `a = a op a op b` or `a = a op b`/`a op= b`. Therefore, it suggests both.
42 /// If `a op= a op b` is really the correct behaviour it should be
43 /// written as `a = a op a op b` as it's less confusing.
51 pub MISREFACTORED_ASSIGN_OP,
53 "having a variable on both sides of an assign op"
56 #[derive(Copy, Clone, Default)]
59 impl LintPass for AssignOps {
60 fn get_lints(&self) -> LintArray {
61 lint_array!(ASSIGN_OP_PATTERN, MISREFACTORED_ASSIGN_OP)
64 fn name(&self) -> &'static str {
69 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
70 #[allow(clippy::too_many_lines)]
71 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
73 hir::ExprKind::AssignOp(op, lhs, rhs) => {
74 if let hir::ExprKind::Binary(binop, l, r) = &rhs.node {
75 if op.node != binop.node {
79 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, l) {
80 lint_misrefactored_assign_op(cx, expr, *op, rhs, lhs, r);
82 // lhs op= l commutative_op r
83 if is_commutative(op.node) && SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, r) {
84 lint_misrefactored_assign_op(cx, expr, *op, rhs, lhs, l);
88 hir::ExprKind::Assign(assignee, e) => {
89 if let hir::ExprKind::Binary(op, l, r) = &e.node {
90 #[allow(clippy::cognitive_complexity)]
91 let lint = |assignee: &hir::Expr, rhs: &hir::Expr| {
92 let ty = cx.tables.expr_ty(assignee);
93 let rty = cx.tables.expr_ty(rhs);
99 $($trait_name:ident),+) => {
101 $(hir::BinOpKind::$trait_name => {
102 let [krate, module] = crate::utils::paths::OPS_MODULE;
103 let path = [krate, module, concat!(stringify!($trait_name), "Assign")];
104 let trait_id = if let Some(trait_id) = get_trait_def_id($cx, &path) {
107 return; // useless if the trait doesn't exist
109 // check that we are not inside an `impl AssignOp` of this exact operation
110 let parent_fn = cx.tcx.hir().get_parent_item(e.hir_id);
112 if let Some(trait_ref) = trait_ref_of_method(cx, parent_fn);
113 if trait_ref.path.def.def_id() == trait_id;
116 implements_trait($cx, $ty, trait_id, &[$rty])
144 "manual implementation of an assign operation",
146 if let (Some(snip_a), Some(snip_r)) =
147 (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span))
152 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
153 Applicability::MachineApplicable,
161 let mut visitor = ExprVisitor {
167 walk_expr(&mut visitor, e);
169 if visitor.counter == 1 {
171 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, l) {
174 // a = b commutative_op a
175 // Limited to primitive type as these ops are know to be commutative
176 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r)
177 && cx.tables.expr_ty(assignee).is_primitive_ty()
181 | hir::BinOpKind::Mul
182 | hir::BinOpKind::And
184 | hir::BinOpKind::BitXor
185 | hir::BinOpKind::BitAnd
186 | hir::BinOpKind::BitOr => {
200 fn lint_misrefactored_assign_op(
201 cx: &LateContext<'_, '_>,
205 assignee: &hir::Expr,
206 rhs_other: &hir::Expr,
210 MISREFACTORED_ASSIGN_OP,
212 "variable appears on both sides of an assignment operation",
214 if let (Some(snip_a), Some(snip_r)) = (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs_other.span)) {
215 let a = &sugg::Sugg::hir(cx, assignee, "..");
216 let r = &sugg::Sugg::hir(cx, rhs, "..");
217 let long = format!("{} = {}", snip_a, sugg::make_binop(higher::binop(op.node), a, r));
221 "Did you mean {} = {} {} {} or {}? Consider replacing it with",
228 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
229 Applicability::MachineApplicable,
235 Applicability::MachineApplicable, // snippet
242 fn is_commutative(op: hir::BinOpKind) -> bool {
243 use rustc::hir::BinOpKind::*;
245 Add | Mul | And | Or | BitXor | BitAnd | BitOr | Eq | Ne => true,
246 Sub | Div | Rem | Shl | Shr | Lt | Le | Ge | Gt => false,
250 struct ExprVisitor<'a, 'tcx: 'a> {
251 assignee: &'a hir::Expr,
253 cx: &'a LateContext<'a, 'tcx>,
256 impl<'a, 'tcx: 'a> Visitor<'tcx> for ExprVisitor<'a, 'tcx> {
257 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
258 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(self.assignee, expr) {
262 walk_expr(self, expr);
264 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
265 NestedVisitorMap::None