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};
9 /// **What it does:** Checks for compound assignment operations (`+=` and
12 /// **Why is this bad?** Projects with many developers from languages without
13 /// those operations may find them unreadable and not worth their weight.
15 /// **Known problems:** Types implementing `OpAssign` don't necessarily
22 declare_clippy_lint! {
25 "any compound assignment operation"
28 /// **What it does:** Checks for `a = a op b` or `a = b commutative_op a`
31 /// **Why is this bad?** These can be written as the shorter `a op= b`.
33 /// **Known problems:** While forbidden by the spec, `OpAssign` traits may have
34 /// implementations that differ from the regular `Op` impl.
42 declare_clippy_lint! {
43 pub ASSIGN_OP_PATTERN,
45 "assigning the result of an operation on a variable to that same variable"
48 /// **What it does:** Checks for `a op= a op b` or `a op= b op a` patterns.
50 /// **Why is this bad?** Most likely these are bugs where one meant to write `a
53 /// **Known problems:** Someone might actually mean `a op= a op b`, but that
54 /// should rather be written as `a = (2 * a) op b` where applicable.
62 declare_clippy_lint! {
63 pub MISREFACTORED_ASSIGN_OP,
65 "having a variable on both sides of an assign op"
68 #[derive(Copy, Clone, Default)]
71 impl LintPass for AssignOps {
72 fn get_lints(&self) -> LintArray {
73 lint_array!(ASSIGN_OPS, ASSIGN_OP_PATTERN, MISREFACTORED_ASSIGN_OP)
77 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
78 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
80 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
81 span_lint_and_then(cx, ASSIGN_OPS, expr.span, "assign operation detected", |db| {
82 let lhs = &sugg::Sugg::hir(cx, lhs, "..");
83 let rhs = &sugg::Sugg::hir(cx, rhs, "..");
88 format!("{} = {}", lhs, sugg::make_binop(higher::binop(op.node), lhs, rhs)),
91 if let hir::ExprKind::Binary(binop, ref l, ref r) = rhs.node {
92 if op.node == binop.node {
93 let lint = |assignee: &hir::Expr, rhs_other: &hir::Expr| {
96 MISREFACTORED_ASSIGN_OP,
98 "variable appears on both sides of an assignment operation",
100 if let (Some(snip_a), Some(snip_r)) =
101 (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs_other.span))
103 let a = &sugg::Sugg::hir(cx, assignee, "..");
104 let r = &sugg::Sugg::hir(cx, rhs, "..");
106 format!("{} = {}", snip_a, sugg::make_binop(higher::binop(op.node), a, r));
110 "Did you mean {} = {} {} {} or {}? Consider replacing it with",
117 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
119 db.span_suggestion(expr.span, "or", long);
125 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, l) {
128 // lhs op= l commutative_op r
129 if is_commutative(op.node) && SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, r) {
135 hir::ExprKind::Assign(ref assignee, ref e) => {
136 if let hir::ExprKind::Binary(op, ref l, ref r) = e.node {
137 #[allow(cyclomatic_complexity)]
138 let lint = |assignee: &hir::Expr, rhs: &hir::Expr| {
139 let ty = cx.tables.expr_ty(assignee);
140 let rty = cx.tables.expr_ty(rhs);
146 $($trait_name:ident),+) => {
148 $(hir::BinOpKind::$trait_name => {
149 let [krate, module] = crate::utils::paths::OPS_MODULE;
150 let path = [krate, module, concat!(stringify!($trait_name), "Assign")];
151 let trait_id = if let Some(trait_id) = get_trait_def_id($cx, &path) {
154 return; // useless if the trait doesn't exist
156 // check that we are not inside an `impl AssignOp` of this exact operation
157 let parent_fn = cx.tcx.hir.get_parent(e.id);
158 let parent_impl = cx.tcx.hir.get_parent(parent_fn);
159 // the crate node is the only one that is not in the map
161 if parent_impl != ast::CRATE_NODE_ID;
162 if let hir::map::Node::NodeItem(item) = cx.tcx.hir.get(parent_impl);
163 if let hir::ItemKind::Impl(_, _, _, _, Some(ref trait_ref), _, _) =
165 if trait_ref.path.def.def_id() == trait_id;
168 implements_trait($cx, $ty, trait_id, &[$rty])
196 "manual implementation of an assign operation",
198 if let (Some(snip_a), Some(snip_r)) =
199 (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span))
204 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
212 let mut visitor = ExprVisitor {
218 walk_expr(&mut visitor, e);
220 if visitor.counter == 1 {
222 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, l) {
225 // a = b commutative_op a
226 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r) {
229 | hir::BinOpKind::Mul
230 | hir::BinOpKind::And
232 | hir::BinOpKind::BitXor
233 | hir::BinOpKind::BitAnd
234 | hir::BinOpKind::BitOr => {
248 fn is_commutative(op: hir::BinOpKind) -> bool {
249 use rustc::hir::BinOpKind::*;
251 Add | Mul | And | Or | BitXor | BitAnd | BitOr | Eq | Ne => true,
252 Sub | Div | Rem | Shl | Shr | Lt | Le | Ge | Gt => false,
256 struct ExprVisitor<'a, 'tcx: 'a> {
257 assignee: &'a hir::Expr,
259 cx: &'a LateContext<'a, 'tcx>,
262 impl<'a, 'tcx: 'a> Visitor<'tcx> for ExprVisitor<'a, 'tcx> {
263 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
264 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(self.assignee, expr) {
268 walk_expr(self, expr);
270 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
271 NestedVisitorMap::None