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;
11 /// **What it does:** Checks for `a = a op b` or `a = b commutative_op a`
14 /// **Why is this bad?** These can be written as the shorter `a op= b`.
16 /// **Known problems:** While forbidden by the spec, `OpAssign` traits may have
17 /// implementations that differ from the regular `Op` impl.
25 declare_clippy_lint! {
26 pub ASSIGN_OP_PATTERN,
28 "assigning the result of an operation on a variable to that same variable"
31 /// **What it does:** Checks for `a op= a op b` or `a op= b op a` patterns.
33 /// **Why is this bad?** Most likely these are bugs where one meant to write `a
36 /// **Known problems:** Clippy cannot know for sure if `a op= a op b` should have
37 /// been `a = a op a op b` or `a = a op b`/`a op= b`. Therefore it suggests both.
38 /// If `a op= a op b` is really the correct behaviour it should be
39 /// written as `a = a op a op b` as it's less confusing.
47 declare_clippy_lint! {
48 pub MISREFACTORED_ASSIGN_OP,
50 "having a variable on both sides of an assign op"
53 #[derive(Copy, Clone, Default)]
56 impl LintPass for AssignOps {
57 fn get_lints(&self) -> LintArray {
58 lint_array!(ASSIGN_OP_PATTERN, MISREFACTORED_ASSIGN_OP)
61 fn name(&self) -> &'static str {
66 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
67 #[allow(clippy::too_many_lines)]
68 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
70 hir::ExprKind::AssignOp(op, lhs, rhs) => {
71 if let hir::ExprKind::Binary(binop, l, r) = &rhs.node {
72 if op.node == binop.node {
73 let lint = |assignee: &hir::Expr, rhs_other: &hir::Expr| {
76 MISREFACTORED_ASSIGN_OP,
78 "variable appears on both sides of an assignment operation",
80 if let (Some(snip_a), Some(snip_r)) =
81 (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs_other.span))
83 let a = &sugg::Sugg::hir(cx, assignee, "..");
84 let r = &sugg::Sugg::hir(cx, rhs, "..");
86 format!("{} = {}", snip_a, sugg::make_binop(higher::binop(op.node), a, r));
90 "Did you mean {} = {} {} {} or {}? Consider replacing it with",
97 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
98 Applicability::MachineApplicable,
104 Applicability::MachineApplicable, // snippet
111 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, l) {
114 // lhs op= l commutative_op r
115 if is_commutative(op.node) && SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, r) {
121 hir::ExprKind::Assign(assignee, e) => {
122 if let hir::ExprKind::Binary(op, l, r) = &e.node {
123 #[allow(clippy::cyclomatic_complexity)]
124 let lint = |assignee: &hir::Expr, rhs: &hir::Expr| {
125 let ty = cx.tables.expr_ty(assignee);
126 let rty = cx.tables.expr_ty(rhs);
132 $($trait_name:ident),+) => {
134 $(hir::BinOpKind::$trait_name => {
135 let [krate, module] = crate::utils::paths::OPS_MODULE;
136 let path = [krate, module, concat!(stringify!($trait_name), "Assign")];
137 let trait_id = if let Some(trait_id) = get_trait_def_id($cx, &path) {
140 return; // useless if the trait doesn't exist
142 // check that we are not inside an `impl AssignOp` of this exact operation
143 let parent_fn = cx.tcx.hir().get_parent(e.id);
144 let parent_impl = cx.tcx.hir().get_parent(parent_fn);
145 // the crate node is the only one that is not in the map
147 if parent_impl != ast::CRATE_NODE_ID;
148 if let hir::Node::Item(item) = cx.tcx.hir().get(parent_impl);
149 if let hir::ItemKind::Impl(_, _, _, _, Some(trait_ref), _, _) =
151 if trait_ref.path.def.def_id() == trait_id;
154 implements_trait($cx, $ty, trait_id, &[$rty])
182 "manual implementation of an assign operation",
184 if let (Some(snip_a), Some(snip_r)) =
185 (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span))
190 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
191 Applicability::MachineApplicable,
199 let mut visitor = ExprVisitor {
205 walk_expr(&mut visitor, e);
207 if visitor.counter == 1 {
209 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, l) {
212 // a = b commutative_op a
213 // Limited to primitive type as these ops are know to be commutative
214 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r)
215 && cx.tables.expr_ty(assignee).is_primitive_ty()
219 | hir::BinOpKind::Mul
220 | hir::BinOpKind::And
222 | hir::BinOpKind::BitXor
223 | hir::BinOpKind::BitAnd
224 | hir::BinOpKind::BitOr => {
238 fn is_commutative(op: hir::BinOpKind) -> bool {
239 use rustc::hir::BinOpKind::*;
241 Add | Mul | And | Or | BitXor | BitAnd | BitOr | Eq | Ne => true,
242 Sub | Div | Rem | Shl | Shr | Lt | Le | Ge | Gt => false,
246 struct ExprVisitor<'a, 'tcx: 'a> {
247 assignee: &'a hir::Expr,
249 cx: &'a LateContext<'a, 'tcx>,
252 impl<'a, 'tcx: 'a> Visitor<'tcx> for ExprVisitor<'a, 'tcx> {
253 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
254 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(self.assignee, expr) {
258 walk_expr(self, expr);
260 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
261 NestedVisitorMap::None