]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/assign_ops.rs
Merge remote-tracking branch 'upstream/master' into rustup
[rust.git] / clippy_lints / src / assign_ops.rs
1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::source::snippet_opt;
3 use clippy_utils::ty::implements_trait;
4 use clippy_utils::{binop_traits, sugg};
5 use clippy_utils::{eq_expr_value, trait_ref_of_method};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir as hir;
9 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::hir::map::Map;
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13
14 declare_clippy_lint! {
15     /// ### What it does
16     /// Checks for `a = a op b` or `a = b commutative_op a`
17     /// patterns.
18     ///
19     /// ### Why is this bad?
20     /// These can be written as the shorter `a op= b`.
21     ///
22     /// ### Known problems
23     /// While forbidden by the spec, `OpAssign` traits may have
24     /// implementations that differ from the regular `Op` impl.
25     ///
26     /// ### Example
27     /// ```rust
28     /// let mut a = 5;
29     /// let b = 0;
30     /// // ...
31     /// // Bad
32     /// a = a + b;
33     ///
34     /// // Good
35     /// a += b;
36     /// ```
37     #[clippy::version = "pre 1.29.0"]
38     pub ASSIGN_OP_PATTERN,
39     style,
40     "assigning the result of an operation on a variable to that same variable"
41 }
42
43 declare_clippy_lint! {
44     /// ### What it does
45     /// Checks for `a op= a op b` or `a op= b op a` patterns.
46     ///
47     /// ### Why is this bad?
48     /// Most likely these are bugs where one meant to write `a
49     /// op= b`.
50     ///
51     /// ### Known problems
52     /// Clippy cannot know for sure if `a op= a op b` should have
53     /// been `a = a op a op b` or `a = a op b`/`a op= b`. Therefore, it suggests both.
54     /// If `a op= a op b` is really the correct behaviour it should be
55     /// written as `a = a op a op b` as it's less confusing.
56     ///
57     /// ### Example
58     /// ```rust
59     /// let mut a = 5;
60     /// let b = 2;
61     /// // ...
62     /// a += a + b;
63     /// ```
64     #[clippy::version = "pre 1.29.0"]
65     pub MISREFACTORED_ASSIGN_OP,
66     suspicious,
67     "having a variable on both sides of an assign op"
68 }
69
70 declare_lint_pass!(AssignOps => [ASSIGN_OP_PATTERN, MISREFACTORED_ASSIGN_OP]);
71
72 impl<'tcx> LateLintPass<'tcx> for AssignOps {
73     #[allow(clippy::too_many_lines)]
74     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
75         match &expr.kind {
76             hir::ExprKind::AssignOp(op, lhs, rhs) => {
77                 if let hir::ExprKind::Binary(binop, l, r) = &rhs.kind {
78                     if op.node != binop.node {
79                         return;
80                     }
81                     // lhs op= l op r
82                     if eq_expr_value(cx, lhs, l) {
83                         lint_misrefactored_assign_op(cx, expr, *op, rhs, lhs, r);
84                     }
85                     // lhs op= l commutative_op r
86                     if is_commutative(op.node) && eq_expr_value(cx, lhs, r) {
87                         lint_misrefactored_assign_op(cx, expr, *op, rhs, lhs, l);
88                     }
89                 }
90             },
91             hir::ExprKind::Assign(assignee, e, _) => {
92                 if let hir::ExprKind::Binary(op, l, r) = &e.kind {
93                     let lint = |assignee: &hir::Expr<'_>, rhs: &hir::Expr<'_>| {
94                         let ty = cx.typeck_results().expr_ty(assignee);
95                         let rty = cx.typeck_results().expr_ty(rhs);
96                         if_chain! {
97                             if let Some((_, lang_item)) = binop_traits(op.node);
98                             if let Ok(trait_id) = cx.tcx.lang_items().require(lang_item);
99                             let parent_fn = cx.tcx.hir().get_parent_item(e.hir_id);
100                             if trait_ref_of_method(cx, parent_fn)
101                                 .map_or(true, |t| t.path.res.def_id() != trait_id);
102                             if implements_trait(cx, ty, trait_id, &[rty.into()]);
103                             then {
104                                 span_lint_and_then(
105                                     cx,
106                                     ASSIGN_OP_PATTERN,
107                                     expr.span,
108                                     "manual implementation of an assign operation",
109                                     |diag| {
110                                         if let (Some(snip_a), Some(snip_r)) =
111                                             (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span))
112                                         {
113                                             diag.span_suggestion(
114                                                 expr.span,
115                                                 "replace it with",
116                                                 format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
117                                                 Applicability::MachineApplicable,
118                                             );
119                                         }
120                                     },
121                                 );
122                             }
123                         }
124                     };
125
126                     let mut visitor = ExprVisitor {
127                         assignee,
128                         counter: 0,
129                         cx,
130                     };
131
132                     walk_expr(&mut visitor, e);
133
134                     if visitor.counter == 1 {
135                         // a = a op b
136                         if eq_expr_value(cx, assignee, l) {
137                             lint(assignee, r);
138                         }
139                         // a = b commutative_op a
140                         // Limited to primitive type as these ops are know to be commutative
141                         if eq_expr_value(cx, assignee, r) && cx.typeck_results().expr_ty(assignee).is_primitive_ty() {
142                             match op.node {
143                                 hir::BinOpKind::Add
144                                 | hir::BinOpKind::Mul
145                                 | hir::BinOpKind::And
146                                 | hir::BinOpKind::Or
147                                 | hir::BinOpKind::BitXor
148                                 | hir::BinOpKind::BitAnd
149                                 | hir::BinOpKind::BitOr => {
150                                     lint(assignee, l);
151                                 },
152                                 _ => {},
153                             }
154                         }
155                     }
156                 }
157             },
158             _ => {},
159         }
160     }
161 }
162
163 fn lint_misrefactored_assign_op(
164     cx: &LateContext<'_>,
165     expr: &hir::Expr<'_>,
166     op: hir::BinOp,
167     rhs: &hir::Expr<'_>,
168     assignee: &hir::Expr<'_>,
169     rhs_other: &hir::Expr<'_>,
170 ) {
171     span_lint_and_then(
172         cx,
173         MISREFACTORED_ASSIGN_OP,
174         expr.span,
175         "variable appears on both sides of an assignment operation",
176         |diag| {
177             if let (Some(snip_a), Some(snip_r)) = (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs_other.span)) {
178                 let a = &sugg::Sugg::hir(cx, assignee, "..");
179                 let r = &sugg::Sugg::hir(cx, rhs, "..");
180                 let long = format!("{} = {}", snip_a, sugg::make_binop(op.node.into(), a, r));
181                 diag.span_suggestion(
182                     expr.span,
183                     &format!(
184                         "did you mean `{} = {} {} {}` or `{}`? Consider replacing it with",
185                         snip_a,
186                         snip_a,
187                         op.node.as_str(),
188                         snip_r,
189                         long
190                     ),
191                     format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
192                     Applicability::MaybeIncorrect,
193                 );
194                 diag.span_suggestion(
195                     expr.span,
196                     "or",
197                     long,
198                     Applicability::MaybeIncorrect, // snippet
199                 );
200             }
201         },
202     );
203 }
204
205 #[must_use]
206 fn is_commutative(op: hir::BinOpKind) -> bool {
207     use rustc_hir::BinOpKind::{
208         Add, And, BitAnd, BitOr, BitXor, Div, Eq, Ge, Gt, Le, Lt, Mul, Ne, Or, Rem, Shl, Shr, Sub,
209     };
210     match op {
211         Add | Mul | And | Or | BitXor | BitAnd | BitOr | Eq | Ne => true,
212         Sub | Div | Rem | Shl | Shr | Lt | Le | Ge | Gt => false,
213     }
214 }
215
216 struct ExprVisitor<'a, 'tcx> {
217     assignee: &'a hir::Expr<'a>,
218     counter: u8,
219     cx: &'a LateContext<'tcx>,
220 }
221
222 impl<'a, 'tcx> Visitor<'tcx> for ExprVisitor<'a, 'tcx> {
223     type Map = Map<'tcx>;
224
225     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
226         if eq_expr_value(self.cx, self.assignee, expr) {
227             self.counter += 1;
228         }
229
230         walk_expr(self, expr);
231     }
232     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
233         NestedVisitorMap::None
234     }
235 }