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