1 use crate::utils::{get_trait_def_id, implements_trait, snippet_opt, span_lint_and_then, SpanlessEq};
2 use crate::utils::{higher, sugg};
4 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
6 use rustc::{declare_lint, lint_array};
7 use if_chain::if_chain;
10 /// **What it does:** Checks for compound assignment operations (`+=` and
13 /// **Why is this bad?** Projects with many developers from languages without
14 /// those operations may find them unreadable and not worth their weight.
16 /// **Known problems:** Types implementing `OpAssign` don't necessarily
23 declare_clippy_lint! {
26 "any compound assignment operation"
29 /// **What it does:** Checks for `a = a op b` or `a = b commutative_op a`
32 /// **Why is this bad?** These can be written as the shorter `a op= b`.
34 /// **Known problems:** While forbidden by the spec, `OpAssign` traits may have
35 /// implementations that differ from the regular `Op` impl.
43 declare_clippy_lint! {
44 pub ASSIGN_OP_PATTERN,
46 "assigning the result of an operation on a variable to that same variable"
49 /// **What it does:** Checks for `a op= a op b` or `a op= b op a` patterns.
51 /// **Why is this bad?** Most likely these are bugs where one meant to write `a
54 /// **Known problems:** Clippy cannot know for sure if `a op= a op b` should have
55 /// been `a = a op a op b` or `a = a op b`/`a op= b`. Therefore it suggests both.
56 /// If `a op= a op b` is really the correct behaviour it should be
57 /// written as `a = a op a op b` as it's less confusing.
65 declare_clippy_lint! {
66 pub MISREFACTORED_ASSIGN_OP,
68 "having a variable on both sides of an assign op"
71 #[derive(Copy, Clone, Default)]
74 impl LintPass for AssignOps {
75 fn get_lints(&self) -> LintArray {
76 lint_array!(ASSIGN_OPS, ASSIGN_OP_PATTERN, MISREFACTORED_ASSIGN_OP)
80 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
81 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
83 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
84 span_lint_and_then(cx, ASSIGN_OPS, expr.span, "assign operation detected", |db| {
85 let lhs = &sugg::Sugg::hir(cx, lhs, "..");
86 let rhs = &sugg::Sugg::hir(cx, rhs, "..");
91 format!("{} = {}", lhs, sugg::make_binop(higher::binop(op.node), lhs, rhs)),
94 if let hir::ExprKind::Binary(binop, ref l, ref r) = rhs.node {
95 if op.node == binop.node {
96 let lint = |assignee: &hir::Expr, rhs_other: &hir::Expr| {
99 MISREFACTORED_ASSIGN_OP,
101 "variable appears on both sides of an assignment operation",
103 if let (Some(snip_a), Some(snip_r)) =
104 (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs_other.span))
106 let a = &sugg::Sugg::hir(cx, assignee, "..");
107 let r = &sugg::Sugg::hir(cx, rhs, "..");
109 format!("{} = {}", snip_a, sugg::make_binop(higher::binop(op.node), a, r));
113 "Did you mean {} = {} {} {} or {}? Consider replacing it with",
120 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
122 db.span_suggestion(expr.span, "or", long);
128 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, l) {
131 // lhs op= l commutative_op r
132 if is_commutative(op.node) && SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, r) {
138 hir::ExprKind::Assign(ref assignee, ref e) => {
139 if let hir::ExprKind::Binary(op, ref l, ref r) = e.node {
140 #[allow(cyclomatic_complexity)]
141 let lint = |assignee: &hir::Expr, rhs: &hir::Expr| {
142 let ty = cx.tables.expr_ty(assignee);
143 let rty = cx.tables.expr_ty(rhs);
149 $($trait_name:ident),+) => {
151 $(hir::BinOpKind::$trait_name => {
152 let [krate, module] = crate::utils::paths::OPS_MODULE;
153 let path = [krate, module, concat!(stringify!($trait_name), "Assign")];
154 let trait_id = if let Some(trait_id) = get_trait_def_id($cx, &path) {
157 return; // useless if the trait doesn't exist
159 // check that we are not inside an `impl AssignOp` of this exact operation
160 let parent_fn = cx.tcx.hir.get_parent(e.id);
161 let parent_impl = cx.tcx.hir.get_parent(parent_fn);
162 // the crate node is the only one that is not in the map
164 if parent_impl != ast::CRATE_NODE_ID;
165 if let hir::map::Node::NodeItem(item) = cx.tcx.hir.get(parent_impl);
166 if let hir::ItemKind::Impl(_, _, _, _, Some(ref trait_ref), _, _) =
168 if trait_ref.path.def.def_id() == trait_id;
171 implements_trait($cx, $ty, trait_id, &[$rty])
199 "manual implementation of an assign operation",
201 if let (Some(snip_a), Some(snip_r)) =
202 (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span))
207 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
215 let mut visitor = ExprVisitor {
221 walk_expr(&mut visitor, e);
223 if visitor.counter == 1 {
225 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, l) {
228 // a = b commutative_op a
229 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r) {
232 | hir::BinOpKind::Mul
233 | hir::BinOpKind::And
235 | hir::BinOpKind::BitXor
236 | hir::BinOpKind::BitAnd
237 | hir::BinOpKind::BitOr => {
251 fn is_commutative(op: hir::BinOpKind) -> bool {
252 use rustc::hir::BinOpKind::*;
254 Add | Mul | And | Or | BitXor | BitAnd | BitOr | Eq | Ne => true,
255 Sub | Div | Rem | Shl | Shr | Lt | Le | Ge | Gt => false,
259 struct ExprVisitor<'a, 'tcx: 'a> {
260 assignee: &'a hir::Expr,
262 cx: &'a LateContext<'a, 'tcx>,
265 impl<'a, 'tcx: 'a> Visitor<'tcx> for ExprVisitor<'a, 'tcx> {
266 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
267 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(self.assignee, expr) {
271 walk_expr(self, expr);
273 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
274 NestedVisitorMap::None