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:** Someone might actually mean `a op= a op b`, but that
55 /// should rather be written as `a = (2 * a) op b` where applicable.
63 declare_clippy_lint! {
64 pub MISREFACTORED_ASSIGN_OP,
66 "having a variable on both sides of an assign op"
69 #[derive(Copy, Clone, Default)]
72 impl LintPass for AssignOps {
73 fn get_lints(&self) -> LintArray {
74 lint_array!(ASSIGN_OPS, ASSIGN_OP_PATTERN, MISREFACTORED_ASSIGN_OP)
78 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
79 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
81 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
82 span_lint_and_then(cx, ASSIGN_OPS, expr.span, "assign operation detected", |db| {
83 let lhs = &sugg::Sugg::hir(cx, lhs, "..");
84 let rhs = &sugg::Sugg::hir(cx, rhs, "..");
89 format!("{} = {}", lhs, sugg::make_binop(higher::binop(op.node), lhs, rhs)),
92 if let hir::ExprKind::Binary(binop, ref l, ref r) = rhs.node {
93 if op.node == binop.node {
94 let lint = |assignee: &hir::Expr, rhs_other: &hir::Expr| {
97 MISREFACTORED_ASSIGN_OP,
99 "variable appears on both sides of an assignment operation",
101 if let (Some(snip_a), Some(snip_r)) =
102 (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs_other.span))
104 let a = &sugg::Sugg::hir(cx, assignee, "..");
105 let r = &sugg::Sugg::hir(cx, rhs, "..");
107 format!("{} = {}", snip_a, sugg::make_binop(higher::binop(op.node), a, r));
111 "Did you mean {} = {} {} {} or {}? Consider replacing it with",
118 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
120 db.span_suggestion(expr.span, "or", long);
126 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, l) {
129 // lhs op= l commutative_op r
130 if is_commutative(op.node) && SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, r) {
136 hir::ExprKind::Assign(ref assignee, ref e) => {
137 if let hir::ExprKind::Binary(op, ref l, ref r) = e.node {
138 #[allow(cyclomatic_complexity)]
139 let lint = |assignee: &hir::Expr, rhs: &hir::Expr| {
140 let ty = cx.tables.expr_ty(assignee);
141 let rty = cx.tables.expr_ty(rhs);
147 $($trait_name:ident),+) => {
149 $(hir::BinOpKind::$trait_name => {
150 let [krate, module] = crate::utils::paths::OPS_MODULE;
151 let path = [krate, module, concat!(stringify!($trait_name), "Assign")];
152 let trait_id = if let Some(trait_id) = get_trait_def_id($cx, &path) {
155 return; // useless if the trait doesn't exist
157 // check that we are not inside an `impl AssignOp` of this exact operation
158 let parent_fn = cx.tcx.hir.get_parent(e.id);
159 let parent_impl = cx.tcx.hir.get_parent(parent_fn);
160 // the crate node is the only one that is not in the map
162 if parent_impl != ast::CRATE_NODE_ID;
163 if let hir::map::Node::NodeItem(item) = cx.tcx.hir.get(parent_impl);
164 if let hir::ItemKind::Impl(_, _, _, _, Some(ref trait_ref), _, _) =
166 if trait_ref.path.def.def_id() == trait_id;
169 implements_trait($cx, $ty, trait_id, &[$rty])
197 "manual implementation of an assign operation",
199 if let (Some(snip_a), Some(snip_r)) =
200 (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span))
205 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
213 let mut visitor = ExprVisitor {
219 walk_expr(&mut visitor, e);
221 if visitor.counter == 1 {
223 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, l) {
226 // a = b commutative_op a
227 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r) {
230 | hir::BinOpKind::Mul
231 | hir::BinOpKind::And
233 | hir::BinOpKind::BitXor
234 | hir::BinOpKind::BitAnd
235 | hir::BinOpKind::BitOr => {
249 fn is_commutative(op: hir::BinOpKind) -> bool {
250 use rustc::hir::BinOpKind::*;
252 Add | Mul | And | Or | BitXor | BitAnd | BitOr | Eq | Ne => true,
253 Sub | Div | Rem | Shl | Shr | Lt | Le | Ge | Gt => false,
257 struct ExprVisitor<'a, 'tcx: 'a> {
258 assignee: &'a hir::Expr,
260 cx: &'a LateContext<'a, 'tcx>,
263 impl<'a, 'tcx: 'a> Visitor<'tcx> for ExprVisitor<'a, 'tcx> {
264 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
265 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(self.assignee, expr) {
269 walk_expr(self, expr);
271 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
272 NestedVisitorMap::None