]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/suspicious_trait_impl.rs
Auto merge of #3987 - phansch:rustfix_option_map_or_none, 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_lint_pass, declare_tool_lint};
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 declare_lint_pass!(SuspiciousImpl => [SUSPICIOUS_ARITHMETIC_IMPL, SUSPICIOUS_OP_ASSIGN_IMPL]);
53
54 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for SuspiciousImpl {
55     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
56         if let hir::ExprKind::Binary(binop, _, _) = expr.node {
57             match binop.node {
58                 hir::BinOpKind::Eq
59                 | hir::BinOpKind::Lt
60                 | hir::BinOpKind::Le
61                 | hir::BinOpKind::Ne
62                 | hir::BinOpKind::Ge
63                 | hir::BinOpKind::Gt => return,
64                 _ => {},
65             }
66             // Check if the binary expression is part of another bi/unary expression
67             // as a child node
68             let mut parent_expr = cx.tcx.hir().get_parent_node_by_hir_id(expr.hir_id);
69             while parent_expr != hir::CRATE_HIR_ID {
70                 if let hir::Node::Expr(e) = cx.tcx.hir().get_by_hir_id(parent_expr) {
71                     match e.node {
72                         hir::ExprKind::Binary(..)
73                         | hir::ExprKind::Unary(hir::UnOp::UnNot, _)
74                         | hir::ExprKind::Unary(hir::UnOp::UnNeg, _) => return,
75                         _ => {},
76                     }
77                 }
78                 parent_expr = cx.tcx.hir().get_parent_node_by_hir_id(parent_expr);
79             }
80             // as a parent node
81             let mut visitor = BinaryExprVisitor { in_binary_expr: false };
82             walk_expr(&mut visitor, expr);
83
84             if visitor.in_binary_expr {
85                 return;
86             }
87
88             if let Some(impl_trait) = check_binop(
89                 cx,
90                 expr,
91                 binop.node,
92                 &["Add", "Sub", "Mul", "Div"],
93                 &[
94                     hir::BinOpKind::Add,
95                     hir::BinOpKind::Sub,
96                     hir::BinOpKind::Mul,
97                     hir::BinOpKind::Div,
98                 ],
99             ) {
100                 span_lint(
101                     cx,
102                     SUSPICIOUS_ARITHMETIC_IMPL,
103                     binop.span,
104                     &format!(r#"Suspicious use of binary operator in `{}` impl"#, impl_trait),
105                 );
106             }
107
108             if let Some(impl_trait) = check_binop(
109                 cx,
110                 expr,
111                 binop.node,
112                 &[
113                     "AddAssign",
114                     "SubAssign",
115                     "MulAssign",
116                     "DivAssign",
117                     "BitAndAssign",
118                     "BitOrAssign",
119                     "BitXorAssign",
120                     "RemAssign",
121                     "ShlAssign",
122                     "ShrAssign",
123                 ],
124                 &[
125                     hir::BinOpKind::Add,
126                     hir::BinOpKind::Sub,
127                     hir::BinOpKind::Mul,
128                     hir::BinOpKind::Div,
129                     hir::BinOpKind::BitAnd,
130                     hir::BinOpKind::BitOr,
131                     hir::BinOpKind::BitXor,
132                     hir::BinOpKind::Rem,
133                     hir::BinOpKind::Shl,
134                     hir::BinOpKind::Shr,
135                 ],
136             ) {
137                 span_lint(
138                     cx,
139                     SUSPICIOUS_OP_ASSIGN_IMPL,
140                     binop.span,
141                     &format!(r#"Suspicious use of binary operator in `{}` impl"#, impl_trait),
142                 );
143             }
144         }
145     }
146 }
147
148 fn check_binop<'a>(
149     cx: &LateContext<'_, '_>,
150     expr: &hir::Expr,
151     binop: hir::BinOpKind,
152     traits: &[&'a str],
153     expected_ops: &[hir::BinOpKind],
154 ) -> Option<&'a str> {
155     let mut trait_ids = vec![];
156     let [krate, module] = crate::utils::paths::OPS_MODULE;
157
158     for t in traits {
159         let path = [krate, module, t];
160         if let Some(trait_id) = get_trait_def_id(cx, &path) {
161             trait_ids.push(trait_id);
162         } else {
163             return None;
164         }
165     }
166
167     // Get the actually implemented trait
168     let parent_fn = cx.tcx.hir().get_parent_item(expr.hir_id);
169
170     if_chain! {
171         if let Some(trait_ref) = trait_ref_of_method(cx, parent_fn);
172         if let Some(idx) = trait_ids.iter().position(|&tid| tid == trait_ref.path.def.def_id());
173         if binop != expected_ops[idx];
174         then{
175             return Some(traits[idx])
176         }
177     }
178
179     None
180 }
181
182 struct BinaryExprVisitor {
183     in_binary_expr: bool,
184 }
185
186 impl<'a, 'tcx: 'a> Visitor<'tcx> for BinaryExprVisitor {
187     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
188         match expr.node {
189             hir::ExprKind::Binary(..)
190             | hir::ExprKind::Unary(hir::UnOp::UnNot, _)
191             | hir::ExprKind::Unary(hir::UnOp::UnNeg, _) => self.in_binary_expr = true,
192             _ => {},
193         }
194
195         walk_expr(self, expr);
196     }
197     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
198         NestedVisitorMap::None
199     }
200 }