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