1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::rustc::hir;
11 use crate::rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::rustc_errors::Applicability;
15 use crate::syntax::ast;
16 use crate::utils::{get_trait_def_id, implements_trait, snippet_opt, span_lint_and_then, SpanlessEq};
17 use crate::utils::{higher, sugg};
18 use if_chain::if_chain;
20 /// **What it does:** Checks for `a = a op b` or `a = b commutative_op a`
23 /// **Why is this bad?** These can be written as the shorter `a op= b`.
25 /// **Known problems:** While forbidden by the spec, `OpAssign` traits may have
26 /// implementations that differ from the regular `Op` impl.
34 declare_clippy_lint! {
35 pub ASSIGN_OP_PATTERN,
37 "assigning the result of an operation on a variable to that same variable"
40 /// **What it does:** Checks for `a op= a op b` or `a op= b op a` patterns.
42 /// **Why is this bad?** Most likely these are bugs where one meant to write `a
45 /// **Known problems:** Clippy cannot know for sure if `a op= a op b` should have
46 /// been `a = a op a op b` or `a = a op b`/`a op= b`. Therefore it suggests both.
47 /// If `a op= a op b` is really the correct behaviour it should be
48 /// written as `a = a op a op b` as it's less confusing.
56 declare_clippy_lint! {
57 pub MISREFACTORED_ASSIGN_OP,
59 "having a variable on both sides of an assign op"
62 #[derive(Copy, Clone, Default)]
65 impl LintPass for AssignOps {
66 fn get_lints(&self) -> LintArray {
67 lint_array!(ASSIGN_OP_PATTERN, MISREFACTORED_ASSIGN_OP)
71 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
72 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
74 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
75 if let hir::ExprKind::Binary(binop, ref l, ref r) = rhs.node {
76 if op.node == binop.node {
77 let lint = |assignee: &hir::Expr, rhs_other: &hir::Expr| {
80 MISREFACTORED_ASSIGN_OP,
82 "variable appears on both sides of an assignment operation",
84 if let (Some(snip_a), Some(snip_r)) =
85 (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs_other.span))
87 let a = &sugg::Sugg::hir(cx, assignee, "..");
88 let r = &sugg::Sugg::hir(cx, rhs, "..");
90 format!("{} = {}", snip_a, sugg::make_binop(higher::binop(op.node), a, r));
91 db.span_suggestion_with_applicability(
94 "Did you mean {} = {} {} {} or {}? Consider replacing it with",
101 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
102 Applicability::MachineApplicable,
104 db.span_suggestion_with_applicability(
108 Applicability::MachineApplicable, // snippet
115 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, l) {
118 // lhs op= l commutative_op r
119 if is_commutative(op.node) && SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, r) {
125 hir::ExprKind::Assign(ref assignee, ref e) => {
126 if let hir::ExprKind::Binary(op, ref l, ref r) = e.node {
127 #[allow(clippy::cyclomatic_complexity)]
128 let lint = |assignee: &hir::Expr, rhs: &hir::Expr| {
129 let ty = cx.tables.expr_ty(assignee);
130 let rty = cx.tables.expr_ty(rhs);
136 $($trait_name:ident),+) => {
138 $(hir::BinOpKind::$trait_name => {
139 let [krate, module] = crate::utils::paths::OPS_MODULE;
140 let path = [krate, module, concat!(stringify!($trait_name), "Assign")];
141 let trait_id = if let Some(trait_id) = get_trait_def_id($cx, &path) {
144 return; // useless if the trait doesn't exist
146 // check that we are not inside an `impl AssignOp` of this exact operation
147 let parent_fn = cx.tcx.hir().get_parent(e.id);
148 let parent_impl = cx.tcx.hir().get_parent(parent_fn);
149 // the crate node is the only one that is not in the map
151 if parent_impl != ast::CRATE_NODE_ID;
152 if let hir::Node::Item(item) = cx.tcx.hir().get(parent_impl);
153 if let hir::ItemKind::Impl(_, _, _, _, Some(ref trait_ref), _, _) =
155 if trait_ref.path.def.def_id() == trait_id;
158 implements_trait($cx, $ty, trait_id, &[$rty])
186 "manual implementation of an assign operation",
188 if let (Some(snip_a), Some(snip_r)) =
189 (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span))
191 db.span_suggestion_with_applicability(
194 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
195 Applicability::MachineApplicable,
203 let mut visitor = ExprVisitor {
209 walk_expr(&mut visitor, e);
211 if visitor.counter == 1 {
213 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, l) {
216 // a = b commutative_op a
217 // Limited to primitive type as these ops are know to be commutative
218 if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r)
219 && cx.tables.expr_ty(assignee).is_primitive_ty()
223 | hir::BinOpKind::Mul
224 | hir::BinOpKind::And
226 | hir::BinOpKind::BitXor
227 | hir::BinOpKind::BitAnd
228 | hir::BinOpKind::BitOr => {
242 fn is_commutative(op: hir::BinOpKind) -> bool {
243 use crate::rustc::hir::BinOpKind::*;
245 Add | Mul | And | Or | BitXor | BitAnd | BitOr | Eq | Ne => true,
246 Sub | Div | Rem | Shl | Shr | Lt | Le | Ge | Gt => false,
250 struct ExprVisitor<'a, 'tcx: 'a> {
251 assignee: &'a hir::Expr,
253 cx: &'a LateContext<'a, 'tcx>,
256 impl<'a, 'tcx: 'a> Visitor<'tcx> for ExprVisitor<'a, 'tcx> {
257 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
258 if SpanlessEq::new(self.cx).ignore_fn().eq_expr(self.assignee, expr) {
262 walk_expr(self, expr);
264 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
265 NestedVisitorMap::None