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