]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/suspicious_trait_impl.rs
Merge pull request #2923 from rust-lang-nursery/kind
[rust.git] / clippy_lints / src / suspicious_trait_impl.rs
1 use rustc::lint::*;
2 use rustc::hir;
3 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
4 use syntax::ast;
5 use crate::utils::{get_trait_def_id, span_lint};
6
7 /// **What it does:** Lints for suspicious operations in impls of arithmetic operators, e.g.
8 /// subtracting elements in an Add impl.
9 ///
10 /// **Why this is bad?** This is probably a typo or copy-and-paste error and not intended.
11 ///
12 /// **Known problems:** None.
13 ///
14 /// **Example:**
15 /// ```rust
16 /// impl Add for Foo {
17 ///     type Output = Foo;
18 ///
19 ///     fn add(self, other: Foo) -> Foo {
20 ///         Foo(self.0 - other.0)
21 ///     }
22 /// }
23 /// ```
24 declare_clippy_lint! {
25     pub SUSPICIOUS_ARITHMETIC_IMPL,
26     correctness,
27     "suspicious use of operators in impl of arithmetic trait"
28 }
29
30 /// **What it does:** Lints for suspicious operations in impls of OpAssign, e.g.
31 /// subtracting elements in an AddAssign impl.
32 ///
33 /// **Why this is bad?** This is probably a typo or copy-and-paste error and not intended.
34 ///
35 /// **Known problems:** None.
36 ///
37 /// **Example:**
38 /// ```rust
39 /// impl AddAssign for Foo {
40 ///     fn add_assign(&mut self, other: Foo) {
41 ///         *self = *self - other;
42 ///     }
43 /// }
44 /// ```
45 declare_clippy_lint! {
46     pub SUSPICIOUS_OP_ASSIGN_IMPL,
47     correctness,
48     "suspicious use of operators in impl of OpAssign trait"
49 }
50
51 #[derive(Copy, Clone)]
52 pub struct SuspiciousImpl;
53
54 impl LintPass for SuspiciousImpl {
55     fn get_lints(&self) -> LintArray {
56         lint_array![SUSPICIOUS_ARITHMETIC_IMPL, SUSPICIOUS_OP_ASSIGN_IMPL]
57     }
58 }
59
60 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for SuspiciousImpl {
61     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
62         if let hir::ExprKind::Binary(binop, _, _) = expr.node {
63             match binop.node {
64                 | hir::BinOpKind::Eq
65                 | hir::BinOpKind::Lt
66                 | hir::BinOpKind::Le
67                 | hir::BinOpKind::Ne
68                 | hir::BinOpKind::Ge
69                 | hir::BinOpKind::Gt
70                 => return,
71                 _ => {},
72             }
73             // Check if the binary expression is part of another bi/unary expression
74             // as a child node
75             let mut parent_expr = cx.tcx.hir.get_parent_node(expr.id);
76             while parent_expr != ast::CRATE_NODE_ID {
77                 if let hir::map::Node::NodeExpr(e) = cx.tcx.hir.get(parent_expr) {
78                     match e.node {
79                         hir::ExprKind::Binary(..)
80                         | hir::ExprKind::Unary(hir::UnOp::UnNot, _)
81                         | hir::ExprKind::Unary(hir::UnOp::UnNeg, _) => return,
82                         _ => {},
83                     }
84                 }
85                 parent_expr = cx.tcx.hir.get_parent_node(parent_expr);
86             }
87             // as a parent node
88             let mut visitor = BinaryExprVisitor {
89                 in_binary_expr: false,
90             };
91             walk_expr(&mut visitor, expr);
92
93             if visitor.in_binary_expr {
94                 return;
95             }
96
97             if let Some(impl_trait) = check_binop(
98                 cx,
99                 expr,
100                 binop.node,
101                 &["Add", "Sub", "Mul", "Div"],
102                 &[
103                     hir::BinOpKind::Add,
104                     hir::BinOpKind::Sub,
105                     hir::BinOpKind::Mul,
106                     hir::BinOpKind::Div,
107                 ],
108             ) {
109                 span_lint(
110                     cx,
111                     SUSPICIOUS_ARITHMETIC_IMPL,
112                     binop.span,
113                     &format!(
114                         r#"Suspicious use of binary operator in `{}` impl"#,
115                         impl_trait
116                     ),
117                 );
118             }
119
120             if let Some(impl_trait) = check_binop(
121                 cx,
122                 expr,
123                 binop.node,
124                 &[
125                     "AddAssign",
126                     "SubAssign",
127                     "MulAssign",
128                     "DivAssign",
129                     "BitAndAssign",
130                     "BitOrAssign",
131                     "BitXorAssign",
132                     "RemAssign",
133                     "ShlAssign",
134                     "ShrAssign",
135                 ],
136                 &[
137                     hir::BinOpKind::Add,
138                     hir::BinOpKind::Sub,
139                     hir::BinOpKind::Mul,
140                     hir::BinOpKind::Div,
141                     hir::BinOpKind::BitAnd,
142                     hir::BinOpKind::BitOr,
143                     hir::BinOpKind::BitXor,
144                     hir::BinOpKind::Rem,
145                     hir::BinOpKind::Shl,
146                     hir::BinOpKind::Shr,
147                 ],
148             ) {
149                 span_lint(
150                     cx,
151                     SUSPICIOUS_OP_ASSIGN_IMPL,
152                     binop.span,
153                     &format!(
154                         r#"Suspicious use of binary operator in `{}` impl"#,
155                         impl_trait
156                     ),
157                 );
158             }
159         }
160     }
161 }
162
163 fn check_binop<'a>(
164     cx: &LateContext,
165     expr: &hir::Expr,
166     binop: hir::BinOpKind,
167     traits: &[&'a str],
168     expected_ops: &[hir::BinOpKind],
169 ) -> Option<&'a str> {
170     let mut trait_ids = vec![];
171     let [krate, module] = crate::utils::paths::OPS_MODULE;
172
173     for t in traits {
174         let path = [krate, module, t];
175         if let Some(trait_id) = get_trait_def_id(cx, &path) {
176             trait_ids.push(trait_id);
177         } else {
178             return None;
179         }
180     }
181
182     // Get the actually implemented trait
183     let parent_fn = cx.tcx.hir.get_parent(expr.id);
184     let parent_impl = cx.tcx.hir.get_parent(parent_fn);
185
186     if_chain! {
187         if parent_impl != ast::CRATE_NODE_ID;
188         if let hir::map::Node::NodeItem(item) = cx.tcx.hir.get(parent_impl);
189         if let hir::ItemKind::Impl(_, _, _, _, Some(ref trait_ref), _, _) = item.node;
190         if let Some(idx) = trait_ids.iter().position(|&tid| tid == trait_ref.path.def.def_id());
191         if binop != expected_ops[idx];
192         then{
193             return Some(traits[idx])
194         }
195     }
196
197     None
198 }
199
200 struct BinaryExprVisitor {
201     in_binary_expr: bool,
202 }
203
204 impl<'a, 'tcx: 'a> Visitor<'tcx> for BinaryExprVisitor {
205     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
206         match expr.node {
207             hir::ExprKind::Binary(..)
208             | hir::ExprKind::Unary(hir::UnOp::UnNot, _)
209             | hir::ExprKind::Unary(hir::UnOp::UnNeg, _) => {
210                 self.in_binary_expr = true
211             },
212             _ => {},
213         }
214
215         walk_expr(self, expr);
216     }
217     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
218         NestedVisitorMap::None
219     }
220 }