]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/suspicious_trait_impl.rs
Merge pull request #2821 from mati865/rust-2018-migration
[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         use rustc::hir::BinOp_::*;
63         if let hir::ExprBinary(binop, _, _) = expr.node {
64             match binop.node {
65                 BiEq | BiLt | BiLe | BiNe | BiGe | BiGt => return,
66                 _ => {},
67             }
68             // Check if the binary expression is part of another bi/unary expression
69             // as a child node
70             let mut parent_expr = cx.tcx.hir.get_parent_node(expr.id);
71             while parent_expr != ast::CRATE_NODE_ID {
72                 if let hir::map::Node::NodeExpr(e) = cx.tcx.hir.get(parent_expr) {
73                     match e.node {
74                         hir::ExprBinary(..)
75                         | hir::ExprUnary(hir::UnOp::UnNot, _)
76                         | hir::ExprUnary(hir::UnOp::UnNeg, _) => return,
77                         _ => {},
78                     }
79                 }
80                 parent_expr = cx.tcx.hir.get_parent_node(parent_expr);
81             }
82             // as a parent node
83             let mut visitor = BinaryExprVisitor {
84                 in_binary_expr: false,
85             };
86             walk_expr(&mut visitor, expr);
87
88             if visitor.in_binary_expr {
89                 return;
90             }
91
92             if let Some(impl_trait) = check_binop(
93                 cx,
94                 expr,
95                 &binop.node,
96                 &["Add", "Sub", "Mul", "Div"],
97                 &[BiAdd, BiSub, BiMul, BiDiv],
98             ) {
99                 span_lint(
100                     cx,
101                     SUSPICIOUS_ARITHMETIC_IMPL,
102                     binop.span,
103                     &format!(
104                         r#"Suspicious use of binary operator in `{}` impl"#,
105                         impl_trait
106                     ),
107                 );
108             }
109
110             if let Some(impl_trait) = check_binop(
111                 cx,
112                 expr,
113                 &binop.node,
114                 &[
115                     "AddAssign",
116                     "SubAssign",
117                     "MulAssign",
118                     "DivAssign",
119                     "BitAndAssign",
120                     "BitOrAssign",
121                     "BitXorAssign",
122                     "RemAssign",
123                     "ShlAssign",
124                     "ShrAssign",
125                 ],
126                 &[
127                     BiAdd, BiSub, BiMul, BiDiv, BiBitAnd, BiBitOr, BiBitXor, BiRem, BiShl, BiShr
128                 ],
129             ) {
130                 span_lint(
131                     cx,
132                     SUSPICIOUS_OP_ASSIGN_IMPL,
133                     binop.span,
134                     &format!(
135                         r#"Suspicious use of binary operator in `{}` impl"#,
136                         impl_trait
137                     ),
138                 );
139             }
140         }
141     }
142 }
143
144 fn check_binop<'a>(
145     cx: &LateContext,
146     expr: &hir::Expr,
147     binop: &hir::BinOp_,
148     traits: &[&'a str],
149     expected_ops: &[hir::BinOp_],
150 ) -> Option<&'a str> {
151     let mut trait_ids = vec![];
152     let [krate, module] = crate::utils::paths::OPS_MODULE;
153
154     for t in traits {
155         let path = [krate, module, t];
156         if let Some(trait_id) = get_trait_def_id(cx, &path) {
157             trait_ids.push(trait_id);
158         } else {
159             return None;
160         }
161     }
162
163     // Get the actually implemented trait
164     let parent_fn = cx.tcx.hir.get_parent(expr.id);
165     let parent_impl = cx.tcx.hir.get_parent(parent_fn);
166
167     if_chain! {
168         if parent_impl != ast::CRATE_NODE_ID;
169         if let hir::map::Node::NodeItem(item) = cx.tcx.hir.get(parent_impl);
170         if let hir::Item_::ItemImpl(_, _, _, _, Some(ref trait_ref), _, _) = item.node;
171         if let Some(idx) = trait_ids.iter().position(|&tid| tid == trait_ref.path.def.def_id());
172         if *binop != expected_ops[idx];
173         then{
174             return Some(traits[idx])
175         }
176     }
177
178     None
179 }
180
181 struct BinaryExprVisitor {
182     in_binary_expr: bool,
183 }
184
185 impl<'a, 'tcx: 'a> Visitor<'tcx> for BinaryExprVisitor {
186     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
187         match expr.node {
188             hir::ExprBinary(..)
189             | hir::ExprUnary(hir::UnOp::UnNot, _)
190             | hir::ExprUnary(hir::UnOp::UnNeg, _) => {
191                 self.in_binary_expr = true
192             },
193             _ => {},
194         }
195
196         walk_expr(self, expr);
197     }
198     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
199         NestedVisitorMap::None
200     }
201 }