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