]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/assign_ops.rs
Run rustfmt
[rust.git] / clippy_lints / src / assign_ops.rs
1 use rustc::hir;
2 use rustc::lint::*;
3 use utils::{span_lint_and_then, span_lint, snippet_opt, SpanlessEq, get_trait_def_id, implements_trait};
4
5 /// **What it does:** This lint checks for `+=` operations and similar
6 ///
7 /// **Why is this bad?** Projects with many developers from languages without those operations
8 ///                      may find them unreadable and not worth their weight
9 ///
10 /// **Known problems:** Types implementing `OpAssign` don't necessarily implement `Op`
11 ///
12 /// **Example:**
13 /// ```
14 /// a += 1;
15 /// ```
16 declare_restriction_lint! {
17     pub ASSIGN_OPS,
18     "Any assignment operation"
19 }
20
21 /// **What it does:** Check for `a = a op b` or `a = b commutative_op a` patterns
22 ///
23 /// **Why is this bad?** These can be written as the shorter `a op= b`
24 ///
25 /// **Known problems:** While forbidden by the spec, `OpAssign` traits may have implementations that differ from the regular `Op` impl
26 ///
27 /// **Example:**
28 ///
29 /// ```
30 /// let mut a = 5;
31 /// ...
32 /// a = a + b;
33 /// ```
34 declare_lint! {
35     pub ASSIGN_OP_PATTERN,
36     Warn,
37     "assigning the result of an operation on a variable to that same variable"
38 }
39
40 #[derive(Copy, Clone, Default)]
41 pub struct AssignOps;
42
43 impl LintPass for AssignOps {
44     fn get_lints(&self) -> LintArray {
45         lint_array!(ASSIGN_OPS, ASSIGN_OP_PATTERN)
46     }
47 }
48
49 impl LateLintPass for AssignOps {
50     fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
51         match expr.node {
52             hir::ExprAssignOp(op, ref lhs, ref rhs) => {
53                 if let (Some(l), Some(r)) = (snippet_opt(cx, lhs.span), snippet_opt(cx, rhs.span)) {
54                     span_lint_and_then(cx, ASSIGN_OPS, expr.span, "assign operation detected", |db| {
55                         match rhs.node {
56                             hir::ExprBinary(op2, _, _) if op2 != op => {
57                                 db.span_suggestion(expr.span,
58                                                    "replace it with",
59                                                    format!("{} = {} {} ({})", l, l, op.node.as_str(), r));
60                             }
61                             _ => {
62                                 db.span_suggestion(expr.span,
63                                                    "replace it with",
64                                                    format!("{} = {} {} {}", l, l, op.node.as_str(), r));
65                             }
66                         }
67                     });
68                 } else {
69                     span_lint(cx, ASSIGN_OPS, expr.span, "assign operation detected");
70                 }
71             }
72             hir::ExprAssign(ref assignee, ref e) => {
73                 if let hir::ExprBinary(op, ref l, ref r) = e.node {
74                     let lint = |assignee: &hir::Expr, rhs: &hir::Expr| {
75                         let ty = cx.tcx.expr_ty(assignee);
76                         if ty.walk_shallow().next().is_some() {
77                             return; // implements_trait does not work with generics
78                         }
79                         let rty = cx.tcx.expr_ty(rhs);
80                         if rty.walk_shallow().next().is_some() {
81                             return; // implements_trait does not work with generics
82                         }
83                         macro_rules! ops {
84                             ($op:expr, $cx:expr, $ty:expr, $rty:expr, $($trait_name:ident:$full_trait_name:ident),+) => {
85                                 match $op {
86                                     $(hir::$full_trait_name => {
87                                         let [krate, module] = ::utils::paths::OPS_MODULE;
88                                         let path = [krate, module, concat!(stringify!($trait_name), "Assign")];
89                                         let trait_id = if let Some(trait_id) = get_trait_def_id($cx, &path) {
90                                             trait_id
91                                         } else {
92                                             return; // useless if the trait doesn't exist
93                                         };
94                                         implements_trait($cx, $ty, trait_id, vec![$rty])
95                                     },)*
96                                     _ => false,
97                                 }
98                             }
99                         }
100                         if ops!(op.node,
101                                 cx,
102                                 ty,
103                                 rty,
104                                 Add: BiAdd,
105                                 Sub: BiSub,
106                                 Mul: BiMul,
107                                 Div: BiDiv,
108                                 Rem: BiRem,
109                                 And: BiAnd,
110                                 Or: BiOr,
111                                 BitAnd: BiBitAnd,
112                                 BitOr: BiBitOr,
113                                 BitXor: BiBitXor,
114                                 Shr: BiShr,
115                                 Shl: BiShl) {
116                             if let (Some(snip_a), Some(snip_r)) = (snippet_opt(cx, assignee.span),
117                                                                    snippet_opt(cx, rhs.span)) {
118                                 span_lint_and_then(cx,
119                                                    ASSIGN_OP_PATTERN,
120                                                    expr.span,
121                                                    "manual implementation of an assign operation",
122                                                    |db| {
123                                                        db.span_suggestion(expr.span,
124                                                                           "replace it with",
125                                                                           format!("{} {}= {}", snip_a, op.node.as_str(), snip_r));
126                                                    });
127                             } else {
128                                 span_lint(cx,
129                                           ASSIGN_OP_PATTERN,
130                                           expr.span,
131                                           "manual implementation of an assign operation");
132                             }
133                         }
134                     };
135                     // a = a op b
136                     if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, l) {
137                         lint(assignee, r);
138                     }
139                     // a = b commutative_op a
140                     if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r) {
141                         match op.node {
142                             hir::BiAdd | hir::BiMul | hir::BiAnd | hir::BiOr | hir::BiBitXor | hir::BiBitAnd |
143                             hir::BiBitOr => {
144                                 lint(assignee, l);
145                             }
146                             _ => {}
147                         }
148                     }
149                 }
150             }
151             _ => {}
152         }
153     }
154 }