]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/suspicious_trait_impl.rs
Auto merge of #81728 - Qwaz:fix-80335, r=joshtriplett
[rust.git] / src / tools / clippy / clippy_lints / src / suspicious_trait_impl.rs
1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::{get_trait_def_id, paths, trait_ref_of_method};
3 use if_chain::if_chain;
4 use rustc_hir as hir;
5 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::hir::map::Map;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9
10 declare_clippy_lint! {
11     /// **What it does:** Lints for suspicious operations in impls of arithmetic operators, e.g.
12     /// subtracting elements in an Add impl.
13     ///
14     /// **Why this is bad?** This is probably a typo or copy-and-paste error and not intended.
15     ///
16     /// **Known problems:** None.
17     ///
18     /// **Example:**
19     /// ```ignore
20     /// impl Add for Foo {
21     ///     type Output = Foo;
22     ///
23     ///     fn add(self, other: Foo) -> Foo {
24     ///         Foo(self.0 - other.0)
25     ///     }
26     /// }
27     /// ```
28     pub SUSPICIOUS_ARITHMETIC_IMPL,
29     correctness,
30     "suspicious use of operators in impl of arithmetic trait"
31 }
32
33 declare_clippy_lint! {
34     /// **What it does:** Lints for suspicious operations in impls of OpAssign, e.g.
35     /// subtracting elements in an AddAssign impl.
36     ///
37     /// **Why this is bad?** This is probably a typo or copy-and-paste error and not intended.
38     ///
39     /// **Known problems:** None.
40     ///
41     /// **Example:**
42     /// ```ignore
43     /// impl AddAssign for Foo {
44     ///     fn add_assign(&mut self, other: Foo) {
45     ///         *self = *self - other;
46     ///     }
47     /// }
48     /// ```
49     pub SUSPICIOUS_OP_ASSIGN_IMPL,
50     correctness,
51     "suspicious use of operators in impl of OpAssign trait"
52 }
53
54 declare_lint_pass!(SuspiciousImpl => [SUSPICIOUS_ARITHMETIC_IMPL, SUSPICIOUS_OP_ASSIGN_IMPL]);
55
56 impl<'tcx> LateLintPass<'tcx> for SuspiciousImpl {
57     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
58         if let hir::ExprKind::Binary(binop, _, _) | hir::ExprKind::AssignOp(binop, ..) = expr.kind {
59             match binop.node {
60                 hir::BinOpKind::Eq
61                 | hir::BinOpKind::Lt
62                 | hir::BinOpKind::Le
63                 | hir::BinOpKind::Ne
64                 | hir::BinOpKind::Ge
65                 | hir::BinOpKind::Gt => return,
66                 _ => {},
67             }
68
69             // Check for more than one binary operation in the implemented function
70             // Linting when multiple operations are involved can result in false positives
71             if_chain! {
72                 let parent_fn = cx.tcx.hir().get_parent_item(expr.hir_id);
73                 if let hir::Node::ImplItem(impl_item) = cx.tcx.hir().get(parent_fn);
74                 if let hir::ImplItemKind::Fn(_, body_id) = impl_item.kind;
75                 let body = cx.tcx.hir().body(body_id);
76                 let mut visitor = BinaryExprVisitor { nb_binops: 0 };
77
78                 then {
79                     walk_expr(&mut visitor, &body.value);
80                     if visitor.nb_binops > 1 {
81                         return;
82                     }
83                 }
84             }
85
86             if let Some(impl_trait) = check_binop(
87                 cx,
88                 expr,
89                 binop.node,
90                 &[
91                     "Add", "Sub", "Mul", "Div", "Rem", "BitAnd", "BitOr", "BitXor", "Shl", "Shr",
92                 ],
93                 &[
94                     hir::BinOpKind::Add,
95                     hir::BinOpKind::Sub,
96                     hir::BinOpKind::Mul,
97                     hir::BinOpKind::Div,
98                     hir::BinOpKind::Rem,
99                     hir::BinOpKind::BitAnd,
100                     hir::BinOpKind::BitOr,
101                     hir::BinOpKind::BitXor,
102                     hir::BinOpKind::Shl,
103                     hir::BinOpKind::Shr,
104                 ],
105             ) {
106                 span_lint(
107                     cx,
108                     SUSPICIOUS_ARITHMETIC_IMPL,
109                     binop.span,
110                     &format!("suspicious use of binary operator in `{}` impl", impl_trait),
111                 );
112             }
113
114             if let Some(impl_trait) = check_binop(
115                 cx,
116                 expr,
117                 binop.node,
118                 &[
119                     "AddAssign",
120                     "SubAssign",
121                     "MulAssign",
122                     "DivAssign",
123                     "BitAndAssign",
124                     "BitOrAssign",
125                     "BitXorAssign",
126                     "RemAssign",
127                     "ShlAssign",
128                     "ShrAssign",
129                 ],
130                 &[
131                     hir::BinOpKind::Add,
132                     hir::BinOpKind::Sub,
133                     hir::BinOpKind::Mul,
134                     hir::BinOpKind::Div,
135                     hir::BinOpKind::BitAnd,
136                     hir::BinOpKind::BitOr,
137                     hir::BinOpKind::BitXor,
138                     hir::BinOpKind::Rem,
139                     hir::BinOpKind::Shl,
140                     hir::BinOpKind::Shr,
141                 ],
142             ) {
143                 span_lint(
144                     cx,
145                     SUSPICIOUS_OP_ASSIGN_IMPL,
146                     binop.span,
147                     &format!("suspicious use of binary operator in `{}` impl", impl_trait),
148                 );
149             }
150         }
151     }
152 }
153
154 fn check_binop(
155     cx: &LateContext<'_>,
156     expr: &hir::Expr<'_>,
157     binop: hir::BinOpKind,
158     traits: &[&'static str],
159     expected_ops: &[hir::BinOpKind],
160 ) -> Option<&'static str> {
161     let mut trait_ids = vec![];
162     let [krate, module] = paths::OPS_MODULE;
163
164     for &t in traits {
165         let path = [krate, module, t];
166         if let Some(trait_id) = get_trait_def_id(cx, &path) {
167             trait_ids.push(trait_id);
168         } else {
169             return None;
170         }
171     }
172
173     // Get the actually implemented trait
174     let parent_fn = cx.tcx.hir().get_parent_item(expr.hir_id);
175
176     if_chain! {
177         if let Some(trait_ref) = trait_ref_of_method(cx, parent_fn);
178         if let Some(idx) = trait_ids.iter().position(|&tid| tid == trait_ref.path.res.def_id());
179         if binop != expected_ops[idx];
180         then{
181             return Some(traits[idx])
182         }
183     }
184
185     None
186 }
187
188 struct BinaryExprVisitor {
189     nb_binops: u32,
190 }
191
192 impl<'tcx> Visitor<'tcx> for BinaryExprVisitor {
193     type Map = Map<'tcx>;
194
195     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
196         match expr.kind {
197             hir::ExprKind::Binary(..)
198             | hir::ExprKind::Unary(hir::UnOp::Not | hir::UnOp::Neg, _)
199             | hir::ExprKind::AssignOp(..) => self.nb_binops += 1,
200             _ => {},
201         }
202
203         walk_expr(self, expr);
204     }
205
206     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
207         NestedVisitorMap::None
208     }
209 }