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