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