]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/assign_ops.rs
Fix rustfmt
[rust.git] / clippy_lints / src / assign_ops.rs
1 use rustc::hir;
2 use rustc::lint::*;
3 use syntax::ast;
4 use utils::{span_lint_and_then, snippet_opt, SpanlessEq, get_trait_def_id, implements_trait};
5 use utils::{higher, sugg};
6
7 /// **What it does:** Checks for compound assignment operations (`+=` and similar).
8 ///
9 /// **Why is this bad?** Projects with many developers from languages without
10 /// those operations may find them unreadable and not worth their weight.
11 ///
12 /// **Known problems:** Types implementing `OpAssign` don't necessarily implement `Op`.
13 ///
14 /// **Example:**
15 /// ```rust
16 /// a += 1;
17 /// ```
18 declare_restriction_lint! {
19     pub ASSIGN_OPS,
20     "any compound assignment operation"
21 }
22
23 /// **What it does:** Checks for `a = a op b` or `a = b commutative_op a` patterns.
24 ///
25 /// **Why is this bad?** These can be written as the shorter `a op= b`.
26 ///
27 /// **Known problems:** While forbidden by the spec, `OpAssign` traits may have
28 /// implementations that differ from the regular `Op` impl.
29 ///
30 /// **Example:**
31 /// ```rust
32 /// let mut a = 5;
33 /// ...
34 /// a = a + b;
35 /// ```
36 declare_lint! {
37     pub ASSIGN_OP_PATTERN,
38     Warn,
39     "assigning the result of an operation on a variable to that same variable"
40 }
41
42 /// **What it does:** Checks for `a op= a op b` or `a op= b op a` patterns.
43 ///
44 /// **Why is this bad?** Most likely these are bugs where one meant to write `a op= b`.
45 ///
46 /// **Known problems:** Someone might actually mean `a op= a op b`, but that
47 /// should rather be written as `a = (2 * a) op b` where applicable.
48 ///
49 /// **Example:**
50 /// ```rust
51 /// let mut a = 5;
52 /// ...
53 /// a += a + b;
54 /// ```
55 declare_lint! {
56     pub MISREFACTORED_ASSIGN_OP,
57     Warn,
58     "having a variable on both sides of an assign op"
59 }
60
61 #[derive(Copy, Clone, Default)]
62 pub struct AssignOps;
63
64 impl LintPass for AssignOps {
65     fn get_lints(&self) -> LintArray {
66         lint_array!(ASSIGN_OPS, ASSIGN_OP_PATTERN, MISREFACTORED_ASSIGN_OP)
67     }
68 }
69
70 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
71     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
72         match expr.node {
73             hir::ExprAssignOp(op, ref lhs, ref rhs) => {
74                 span_lint_and_then(cx, ASSIGN_OPS, expr.span, "assign operation detected", |db| {
75                     let lhs = &sugg::Sugg::hir(cx, lhs, "..");
76                     let rhs = &sugg::Sugg::hir(cx, rhs, "..");
77
78                     db.span_suggestion(expr.span,
79                                        "replace it with",
80                                        format!("{} = {}", lhs, sugg::make_binop(higher::binop(op.node), lhs, rhs)));
81                 });
82                 if let hir::ExprBinary(binop, ref l, ref r) = rhs.node {
83                     if op.node == binop.node {
84                         let lint = |assignee: &hir::Expr, rhs: &hir::Expr| {
85                             let ty = cx.tables.expr_ty(assignee);
86                             if ty.walk_shallow().next().is_some() {
87                                 return; // implements_trait does not work with generics
88                             }
89                             let rty = cx.tables.expr_ty(rhs);
90                             if rty.walk_shallow().next().is_some() {
91                                 return; // implements_trait does not work with generics
92                             }
93                             span_lint_and_then(cx,
94                                                MISREFACTORED_ASSIGN_OP,
95                                                expr.span,
96                                                "variable appears on both sides of an assignment operation",
97                                                |db| if let (Some(snip_a), Some(snip_r)) =
98                                                    (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span)) {
99                                                    db.span_suggestion(expr.span,
100                                                                       "replace it with",
101                                                                       format!("{} {}= {}",
102                                                                               snip_a,
103                                                                               op.node.as_str(),
104                                                                               snip_r));
105                                                });
106                         };
107                         // lhs op= l op r
108                         if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, l) {
109                             lint(lhs, r);
110                         }
111                         // lhs op= l commutative_op r
112                         if is_commutative(op.node) && SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, r) {
113                             lint(lhs, l);
114                         }
115                     }
116                 }
117             },
118             hir::ExprAssign(ref assignee, ref e) => {
119                 if let hir::ExprBinary(op, ref l, ref r) = e.node {
120                     #[allow(cyclomatic_complexity)]
121                     let lint = |assignee: &hir::Expr, rhs: &hir::Expr| {
122                         let ty = cx.tables.expr_ty(assignee);
123                         if ty.walk_shallow().next().is_some() {
124                             return; // implements_trait does not work with generics
125                         }
126                         let rty = cx.tables.expr_ty(rhs);
127                         if rty.walk_shallow().next().is_some() {
128                             return; // implements_trait does not work with generics
129                         }
130                         macro_rules! ops {
131                             ($op:expr,
132                              $cx:expr,
133                              $ty:expr,
134                              $rty:expr,
135                              $($trait_name:ident:$full_trait_name:ident),+) => {
136                                 match $op {
137                                     $(hir::$full_trait_name => {
138                                         let [krate, module] = ::utils::paths::OPS_MODULE;
139                                         let path = [krate, module, concat!(stringify!($trait_name), "Assign")];
140                                         let trait_id = if let Some(trait_id) = get_trait_def_id($cx, &path) {
141                                             trait_id
142                                         } else {
143                                             return; // useless if the trait doesn't exist
144                                         };
145                                         // check that we are not inside an `impl AssignOp` of this exact operation
146                                         let parent_fn = cx.tcx.map.get_parent(e.id);
147                                         let parent_impl = cx.tcx.map.get_parent(parent_fn);
148                                         // the crate node is the only one that is not in the map
149                                         if_let_chain!{[
150                                             parent_impl != ast::CRATE_NODE_ID,
151                                             let hir::map::Node::NodeItem(item) = cx.tcx.map.get(parent_impl),
152                                             let hir::Item_::ItemImpl(_, _, _, Some(ref trait_ref), _, _) = item.node,
153                                             trait_ref.path.def.def_id() == trait_id
154                                         ], { return; }}
155                                         implements_trait($cx, $ty, trait_id, vec![$rty])
156                                     },)*
157                                     _ => false,
158                                 }
159                             }
160                         }
161                         if ops!(op.node,
162                                 cx,
163                                 ty,
164                                 rty,
165                                 Add: BiAdd,
166                                 Sub: BiSub,
167                                 Mul: BiMul,
168                                 Div: BiDiv,
169                                 Rem: BiRem,
170                                 And: BiAnd,
171                                 Or: BiOr,
172                                 BitAnd: BiBitAnd,
173                                 BitOr: BiBitOr,
174                                 BitXor: BiBitXor,
175                                 Shr: BiShr,
176                                 Shl: BiShl) {
177                             span_lint_and_then(cx,
178                                                ASSIGN_OP_PATTERN,
179                                                expr.span,
180                                                "manual implementation of an assign operation",
181                                                |db| if let (Some(snip_a), Some(snip_r)) =
182                                                    (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span)) {
183                                                    db.span_suggestion(expr.span,
184                                                                       "replace it with",
185                                                                       format!("{} {}= {}",
186                                                                               snip_a,
187                                                                               op.node.as_str(),
188                                                                               snip_r));
189                                                });
190                         }
191                     };
192                     // a = a op b
193                     if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, l) {
194                         lint(assignee, r);
195                     }
196                     // a = b commutative_op a
197                     if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r) {
198                         match op.node {
199                             hir::BiAdd | hir::BiMul | hir::BiAnd | hir::BiOr | hir::BiBitXor | hir::BiBitAnd |
200                             hir::BiBitOr => {
201                                 lint(assignee, l);
202                             },
203                             _ => {},
204                         }
205                     }
206                 }
207             },
208             _ => {},
209         }
210     }
211 }
212
213 fn is_commutative(op: hir::BinOp_) -> bool {
214     use rustc::hir::BinOp_::*;
215     match op {
216         BiAdd | BiMul | BiAnd | BiOr | BiBitXor | BiBitAnd | BiBitOr | BiEq | BiNe => true,
217         BiSub | BiDiv | BiRem | BiShl | BiShr | BiLt | BiLe | BiGe | BiGt => false,
218     }
219 }