]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/suspicious_trait_impl.rs
Auto merge of #83213 - rylev:update-lints-to-errors, r=nikomatsakis
[rust.git] / 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             let parent_fn = cx.tcx.hir().get_parent_item(expr.hir_id);
72             if_chain! {
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                 then {
76                     let body = cx.tcx.hir().body(body_id);
77                     let mut visitor = BinaryExprVisitor { nb_binops: 0 };
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] = 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 }