1 use crate::utils::{get_trait_def_id, implements_trait, snippet_opt, span_lint_and_then, SpanlessEq};
2 use crate::utils::{higher, sugg};
3 use if_chain::if_chain;
5 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::{declare_tool_lint, lint_array};
8 use rustc_errors::Applicability;
10 /// **What it does:** Checks for `a = a op b` or `a = b commutative_op a`
13 /// **Why is this bad?** These can be written as the shorter `a op= b`.
15 /// **Known problems:** While forbidden by the spec, `OpAssign` traits may have
16 /// implementations that differ from the regular `Op` impl.
24 declare_clippy_lint! {
25 pub ASSIGN_OP_PATTERN,
27 "assigning the result of an operation on a variable to that same variable"
30 /// **What it does:** Checks for `a op= a op b` or `a op= b op a` patterns.
32 /// **Why is this bad?** Most likely these are bugs where one meant to write `a
35 /// **Known problems:** Clippy cannot know for sure if `a op= a op b` should have
36 /// been `a = a op a op b` or `a = a op b`/`a op= b`. Therefore it suggests both.
37 /// If `a op= a op b` is really the correct behaviour it should be
38 /// written as `a = a op a op b` as it's less confusing.
46 declare_clippy_lint! {
47 pub MISREFACTORED_ASSIGN_OP,
49 "having a variable on both sides of an assign op"
52 #[derive(Copy, Clone, Default)]
55 impl LintPass for AssignOps {
56 fn get_lints(&self) -> LintArray {
57 lint_array!(ASSIGN_OP_PATTERN, MISREFACTORED_ASSIGN_OP)
60 fn name(&self) -> &'static str {
65 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
66 #[allow(clippy::too_many_lines)]
67 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
69 hir::ExprKind::AssignOp(op, lhs, rhs) => {
70 if let hir::ExprKind::Binary(binop, l, r) = &rhs.node {
71 if op.node == binop.node {
72 let lint = |assignee: &hir::Expr, rhs_other: &hir::Expr| {
75 MISREFACTORED_ASSIGN_OP,
77 "variable appears on both sides of an assignment operation",
79 if let (Some(snip_a), Some(snip_r)) =
80 (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs_other.span))
82 let a = &sugg::Sugg::hir(cx, assignee, "..");
83 let r = &sugg::Sugg::hir(cx, rhs, "..");
85 format!("{} = {}", snip_a, sugg::make_binop(higher::binop(op.node), a, r));
89 "Did you mean {} = {} {} {} or {}? Consider replacing it with",
96 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
97 Applicability::MachineApplicable,
103 Applicability::MachineApplicable, // snippet
110 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, l) {
113 // lhs op= l commutative_op r
114 if is_commutative(op.node) && SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, r) {
120 hir::ExprKind::Assign(assignee, e) => {
121 if let hir::ExprKind::Binary(op, l, r) = &e.node {
122 #[allow(clippy::cyclomatic_complexity)]
123 let lint = |assignee: &hir::Expr, rhs: &hir::Expr| {
124 let ty = cx.tables.expr_ty(assignee);
125 let rty = cx.tables.expr_ty(rhs);
131 $($trait_name:ident),+) => {
133 $(hir::BinOpKind::$trait_name => {
134 let [krate, module] = crate::utils::paths::OPS_MODULE;
135 let path = [krate, module, concat!(stringify!($trait_name), "Assign")];
136 let trait_id = if let Some(trait_id) = get_trait_def_id($cx, &path) {
139 return; // useless if the trait doesn't exist
141 // check that we are not inside an `impl AssignOp` of this exact operation
142 let parent_fn = cx.tcx.hir().get_parent_item(e.hir_id);
143 let parent_impl = cx.tcx.hir().get_parent_item(parent_fn);
144 // the crate node is the only one that is not in the map
146 if parent_impl != hir::CRATE_HIR_ID;
147 if let hir::Node::Item(item) = cx.tcx.hir().get_by_hir_id(parent_impl);
148 if let hir::ItemKind::Impl(_, _, _, _, Some(trait_ref), _, _) =
150 if trait_ref.path.def.def_id() == trait_id;
153 implements_trait($cx, $ty, trait_id, &[$rty])
181 "manual implementation of an assign operation",
183 if let (Some(snip_a), Some(snip_r)) =
184 (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span))
189 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
190 Applicability::MachineApplicable,
198 let mut visitor = ExprVisitor {
204 walk_expr(&mut visitor, e);
206 if visitor.counter == 1 {
208 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, l) {
211 // a = b commutative_op a
212 // Limited to primitive type as these ops are know to be commutative
213 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r)
214 && cx.tables.expr_ty(assignee).is_primitive_ty()
218 | hir::BinOpKind::Mul
219 | hir::BinOpKind::And
221 | hir::BinOpKind::BitXor
222 | hir::BinOpKind::BitAnd
223 | hir::BinOpKind::BitOr => {
237 fn is_commutative(op: hir::BinOpKind) -> bool {
238 use rustc::hir::BinOpKind::*;
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: 'a> {
246 assignee: &'a hir::Expr,
248 cx: &'a LateContext<'a, 'tcx>,
251 impl<'a, 'tcx: 'a> Visitor<'tcx> for ExprVisitor<'a, 'tcx> {
252 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
253 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(self.assignee, expr) {
257 walk_expr(self, expr);
259 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
260 NestedVisitorMap::None