]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/suspicious_trait_impl.rs
Auto merge of #3519 - phansch:brave_newer_ui_tests, r=flip1995
[rust.git] / clippy_lints / src / suspicious_trait_impl.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::utils::{get_trait_def_id, span_lint};
11 use if_chain::if_chain;
12 use rustc::hir;
13 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
14 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
15 use rustc::{declare_tool_lint, lint_array};
16 use syntax::ast;
17
18 /// **What it does:** Lints for suspicious operations in impls of arithmetic operators, e.g.
19 /// subtracting elements in an Add impl.
20 ///
21 /// **Why this is bad?** This is probably a typo or copy-and-paste error and not intended.
22 ///
23 /// **Known problems:** None.
24 ///
25 /// **Example:**
26 /// ```rust
27 /// impl Add for Foo {
28 ///     type Output = Foo;
29 ///
30 ///     fn add(self, other: Foo) -> Foo {
31 ///         Foo(self.0 - other.0)
32 ///     }
33 /// }
34 /// ```
35 declare_clippy_lint! {
36     pub SUSPICIOUS_ARITHMETIC_IMPL,
37     correctness,
38     "suspicious use of operators in impl of arithmetic trait"
39 }
40
41 /// **What it does:** Lints for suspicious operations in impls of OpAssign, e.g.
42 /// subtracting elements in an AddAssign impl.
43 ///
44 /// **Why this is bad?** This is probably a typo or copy-and-paste error and not intended.
45 ///
46 /// **Known problems:** None.
47 ///
48 /// **Example:**
49 /// ```rust
50 /// impl AddAssign for Foo {
51 ///     fn add_assign(&mut self, other: Foo) {
52 ///         *self = *self - other;
53 ///     }
54 /// }
55 /// ```
56 declare_clippy_lint! {
57     pub SUSPICIOUS_OP_ASSIGN_IMPL,
58     correctness,
59     "suspicious use of operators in impl of OpAssign trait"
60 }
61
62 #[derive(Copy, Clone)]
63 pub struct SuspiciousImpl;
64
65 impl LintPass for SuspiciousImpl {
66     fn get_lints(&self) -> LintArray {
67         lint_array![SUSPICIOUS_ARITHMETIC_IMPL, SUSPICIOUS_OP_ASSIGN_IMPL]
68     }
69 }
70
71 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for SuspiciousImpl {
72     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
73         if let hir::ExprKind::Binary(binop, _, _) = expr.node {
74             match binop.node {
75                 hir::BinOpKind::Eq
76                 | hir::BinOpKind::Lt
77                 | hir::BinOpKind::Le
78                 | hir::BinOpKind::Ne
79                 | hir::BinOpKind::Ge
80                 | hir::BinOpKind::Gt => return,
81                 _ => {},
82             }
83             // Check if the binary expression is part of another bi/unary expression
84             // as a child node
85             let mut parent_expr = cx.tcx.hir().get_parent_node(expr.id);
86             while parent_expr != ast::CRATE_NODE_ID {
87                 if let hir::Node::Expr(e) = cx.tcx.hir().get(parent_expr) {
88                     match e.node {
89                         hir::ExprKind::Binary(..)
90                         | hir::ExprKind::Unary(hir::UnOp::UnNot, _)
91                         | hir::ExprKind::Unary(hir::UnOp::UnNeg, _) => return,
92                         _ => {},
93                     }
94                 }
95                 parent_expr = cx.tcx.hir().get_parent_node(parent_expr);
96             }
97             // as a parent node
98             let mut visitor = BinaryExprVisitor { in_binary_expr: false };
99             walk_expr(&mut visitor, expr);
100
101             if visitor.in_binary_expr {
102                 return;
103             }
104
105             if let Some(impl_trait) = check_binop(
106                 cx,
107                 expr,
108                 binop.node,
109                 &["Add", "Sub", "Mul", "Div"],
110                 &[
111                     hir::BinOpKind::Add,
112                     hir::BinOpKind::Sub,
113                     hir::BinOpKind::Mul,
114                     hir::BinOpKind::Div,
115                 ],
116             ) {
117                 span_lint(
118                     cx,
119                     SUSPICIOUS_ARITHMETIC_IMPL,
120                     binop.span,
121                     &format!(r#"Suspicious use of binary operator in `{}` impl"#, impl_trait),
122                 );
123             }
124
125             if let Some(impl_trait) = check_binop(
126                 cx,
127                 expr,
128                 binop.node,
129                 &[
130                     "AddAssign",
131                     "SubAssign",
132                     "MulAssign",
133                     "DivAssign",
134                     "BitAndAssign",
135                     "BitOrAssign",
136                     "BitXorAssign",
137                     "RemAssign",
138                     "ShlAssign",
139                     "ShrAssign",
140                 ],
141                 &[
142                     hir::BinOpKind::Add,
143                     hir::BinOpKind::Sub,
144                     hir::BinOpKind::Mul,
145                     hir::BinOpKind::Div,
146                     hir::BinOpKind::BitAnd,
147                     hir::BinOpKind::BitOr,
148                     hir::BinOpKind::BitXor,
149                     hir::BinOpKind::Rem,
150                     hir::BinOpKind::Shl,
151                     hir::BinOpKind::Shr,
152                 ],
153             ) {
154                 span_lint(
155                     cx,
156                     SUSPICIOUS_OP_ASSIGN_IMPL,
157                     binop.span,
158                     &format!(r#"Suspicious use of binary operator in `{}` impl"#, impl_trait),
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::Node::Item(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, _) => self.in_binary_expr = true,
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 }