2 get_trait_def_id, implements_trait, snippet_opt, span_lint_and_then, trait_ref_of_method, SpanlessEq,
4 use crate::utils::{higher, sugg};
5 use if_chain::if_chain;
7 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
8 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
9 use rustc::{declare_tool_lint, lint_array};
10 use rustc_errors::Applicability;
12 declare_clippy_lint! {
13 /// **What it does:** Checks for `a = a op b` or `a = b commutative_op a`
16 /// **Why is this bad?** These can be written as the shorter `a op= b`.
18 /// **Known problems:** While forbidden by the spec, `OpAssign` traits may have
19 /// implementations that differ from the regular `Op` impl.
27 pub ASSIGN_OP_PATTERN,
29 "assigning the result of an operation on a variable to that same variable"
32 declare_clippy_lint! {
33 /// **What it does:** Checks for `a op= a op b` or `a op= b op a` patterns.
35 /// **Why is this bad?** Most likely these are bugs where one meant to write `a
38 /// **Known problems:** Clippy cannot know for sure if `a op= a op b` should have
39 /// been `a = a op a op b` or `a = a op b`/`a op= b`. Therefore it suggests both.
40 /// If `a op= a op b` is really the correct behaviour it should be
41 /// written as `a = a op a op b` as it's less confusing.
49 pub MISREFACTORED_ASSIGN_OP,
51 "having a variable on both sides of an assign op"
54 #[derive(Copy, Clone, Default)]
57 impl LintPass for AssignOps {
58 fn get_lints(&self) -> LintArray {
59 lint_array!(ASSIGN_OP_PATTERN, MISREFACTORED_ASSIGN_OP)
62 fn name(&self) -> &'static str {
67 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
68 #[allow(clippy::too_many_lines)]
69 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
71 hir::ExprKind::AssignOp(op, lhs, rhs) => {
72 if let hir::ExprKind::Binary(binop, l, r) = &rhs.node {
73 if op.node != binop.node {
77 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, l) {
78 lint_misrefactored_assign_op(cx, expr, *op, rhs, lhs, r);
80 // lhs op= l commutative_op r
81 if is_commutative(op.node) && SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, r) {
82 lint_misrefactored_assign_op(cx, expr, *op, rhs, lhs, l);
86 hir::ExprKind::Assign(assignee, e) => {
87 if let hir::ExprKind::Binary(op, l, r) = &e.node {
88 #[allow(clippy::cognitive_complexity)]
89 let lint = |assignee: &hir::Expr, rhs: &hir::Expr| {
90 let ty = cx.tables.expr_ty(assignee);
91 let rty = cx.tables.expr_ty(rhs);
97 $($trait_name:ident),+) => {
99 $(hir::BinOpKind::$trait_name => {
100 let [krate, module] = crate::utils::paths::OPS_MODULE;
101 let path = [krate, module, concat!(stringify!($trait_name), "Assign")];
102 let trait_id = if let Some(trait_id) = get_trait_def_id($cx, &path) {
105 return; // useless if the trait doesn't exist
107 // check that we are not inside an `impl AssignOp` of this exact operation
108 let parent_fn = cx.tcx.hir().get_parent_item(e.hir_id);
110 if let Some(trait_ref) = trait_ref_of_method(cx, parent_fn);
111 if trait_ref.path.def.def_id() == trait_id;
114 implements_trait($cx, $ty, trait_id, &[$rty])
142 "manual implementation of an assign operation",
144 if let (Some(snip_a), Some(snip_r)) =
145 (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span))
150 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
151 Applicability::MachineApplicable,
159 let mut visitor = ExprVisitor {
165 walk_expr(&mut visitor, e);
167 if visitor.counter == 1 {
169 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, l) {
172 // a = b commutative_op a
173 // Limited to primitive type as these ops are know to be commutative
174 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r)
175 && cx.tables.expr_ty(assignee).is_primitive_ty()
179 | hir::BinOpKind::Mul
180 | hir::BinOpKind::And
182 | hir::BinOpKind::BitXor
183 | hir::BinOpKind::BitAnd
184 | hir::BinOpKind::BitOr => {
198 fn lint_misrefactored_assign_op(
199 cx: &LateContext<'_, '_>,
203 assignee: &hir::Expr,
204 rhs_other: &hir::Expr,
208 MISREFACTORED_ASSIGN_OP,
210 "variable appears on both sides of an assignment operation",
212 if let (Some(snip_a), Some(snip_r)) = (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs_other.span)) {
213 let a = &sugg::Sugg::hir(cx, assignee, "..");
214 let r = &sugg::Sugg::hir(cx, rhs, "..");
215 let long = format!("{} = {}", snip_a, sugg::make_binop(higher::binop(op.node), a, r));
219 "Did you mean {} = {} {} {} or {}? Consider replacing it with",
226 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
227 Applicability::MachineApplicable,
233 Applicability::MachineApplicable, // snippet
240 fn is_commutative(op: hir::BinOpKind) -> bool {
241 use rustc::hir::BinOpKind::*;
243 Add | Mul | And | Or | BitXor | BitAnd | BitOr | Eq | Ne => true,
244 Sub | Div | Rem | Shl | Shr | Lt | Le | Ge | Gt => false,
248 struct ExprVisitor<'a, 'tcx: 'a> {
249 assignee: &'a hir::Expr,
251 cx: &'a LateContext<'a, 'tcx>,
254 impl<'a, 'tcx: 'a> Visitor<'tcx> for ExprVisitor<'a, 'tcx> {
255 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
256 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(self.assignee, expr) {
260 walk_expr(self, expr);
262 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
263 NestedVisitorMap::None