]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/suspicious_trait_impl.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[rust.git] / clippy_lints / src / suspicious_trait_impl.rs
1 use crate::utils::{get_trait_def_id, span_lint, trait_ref_of_method};
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 declare_clippy_lint! {
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     /// ```ignore
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     pub SUSPICIOUS_ARITHMETIC_IMPL,
27     correctness,
28     "suspicious use of operators in impl of arithmetic trait"
29 }
30
31 declare_clippy_lint! {
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     /// ```ignore
41     /// impl AddAssign for Foo {
42     ///     fn add_assign(&mut self, other: Foo) {
43     ///         *self = *self - other;
44     ///     }
45     /// }
46     /// ```
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
181     if_chain! {
182         if let Some(trait_ref) = trait_ref_of_method(cx, parent_fn);
183         if let Some(idx) = trait_ids.iter().position(|&tid| tid == trait_ref.path.def.def_id());
184         if binop != expected_ops[idx];
185         then{
186             return Some(traits[idx])
187         }
188     }
189
190     None
191 }
192
193 struct BinaryExprVisitor {
194     in_binary_expr: bool,
195 }
196
197 impl<'a, 'tcx: 'a> Visitor<'tcx> for BinaryExprVisitor {
198     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
199         match expr.node {
200             hir::ExprKind::Binary(..)
201             | hir::ExprKind::Unary(hir::UnOp::UnNot, _)
202             | hir::ExprKind::Unary(hir::UnOp::UnNeg, _) => self.in_binary_expr = true,
203             _ => {},
204         }
205
206         walk_expr(self, expr);
207     }
208     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
209         NestedVisitorMap::None
210     }
211 }