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