]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/derive.rs
Rollup merge of #70563 - GuillaumeGomez:page-hash-handling, r=ollie27,kinnison
[rust.git] / src / tools / clippy / clippy_lints / src / derive.rs
1 use crate::utils::paths;
2 use crate::utils::{
3     is_automatically_derived, is_copy, match_path, span_lint_and_help, span_lint_and_note, span_lint_and_then,
4 };
5 use if_chain::if_chain;
6 use rustc_hir::def_id::DefId;
7 use rustc_hir::intravisit::{walk_expr, walk_fn, walk_item, FnKind, NestedVisitorMap, Visitor};
8 use rustc_hir::{
9     BlockCheckMode, BodyId, Expr, ExprKind, FnDecl, HirId, Item, ItemKind, TraitRef, UnsafeSource, Unsafety,
10 };
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_middle::hir::map::Map;
13 use rustc_middle::ty::{self, Ty};
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
15 use rustc_span::source_map::Span;
16
17 declare_clippy_lint! {
18     /// **What it does:** Checks for deriving `Hash` but implementing `PartialEq`
19     /// explicitly or vice versa.
20     ///
21     /// **Why is this bad?** The implementation of these traits must agree (for
22     /// example for use with `HashMap`) so it’s probably a bad idea to use a
23     /// default-generated `Hash` implementation with an explicitly defined
24     /// `PartialEq`. In particular, the following must hold for any type:
25     ///
26     /// ```text
27     /// k1 == k2 ⇒ hash(k1) == hash(k2)
28     /// ```
29     ///
30     /// **Known problems:** None.
31     ///
32     /// **Example:**
33     /// ```ignore
34     /// #[derive(Hash)]
35     /// struct Foo;
36     ///
37     /// impl PartialEq for Foo {
38     ///     ...
39     /// }
40     /// ```
41     pub DERIVE_HASH_XOR_EQ,
42     correctness,
43     "deriving `Hash` but implementing `PartialEq` explicitly"
44 }
45
46 declare_clippy_lint! {
47     /// **What it does:** Checks for explicit `Clone` implementations for `Copy`
48     /// types.
49     ///
50     /// **Why is this bad?** To avoid surprising behaviour, these traits should
51     /// agree and the behaviour of `Copy` cannot be overridden. In almost all
52     /// situations a `Copy` type should have a `Clone` implementation that does
53     /// nothing more than copy the object, which is what `#[derive(Copy, Clone)]`
54     /// gets you.
55     ///
56     /// **Known problems:** Bounds of generic types are sometimes wrong: https://github.com/rust-lang/rust/issues/26925
57     ///
58     /// **Example:**
59     /// ```rust,ignore
60     /// #[derive(Copy)]
61     /// struct Foo;
62     ///
63     /// impl Clone for Foo {
64     ///     // ..
65     /// }
66     /// ```
67     pub EXPL_IMPL_CLONE_ON_COPY,
68     pedantic,
69     "implementing `Clone` explicitly on `Copy` types"
70 }
71
72 declare_clippy_lint! {
73     /// **What it does:** Checks for deriving `serde::Deserialize` on a type that
74     /// has methods using `unsafe`.
75     ///
76     /// **Why is this bad?** Deriving `serde::Deserialize` will create a constructor
77     /// that may violate invariants hold by another constructor.
78     ///
79     /// **Known problems:** None.
80     ///
81     /// **Example:**
82     ///
83     /// ```rust,ignore
84     /// use serde::Deserialize;
85     ///
86     /// #[derive(Deserialize)]
87     /// pub struct Foo {
88     ///     // ..
89     /// }
90     ///
91     /// impl Foo {
92     ///     pub fn new() -> Self {
93     ///         // setup here ..
94     ///     }
95     ///
96     ///     pub unsafe fn parts() -> (&str, &str) {
97     ///         // assumes invariants hold
98     ///     }
99     /// }
100     /// ```
101     pub UNSAFE_DERIVE_DESERIALIZE,
102     pedantic,
103     "deriving `serde::Deserialize` on a type that has methods using `unsafe`"
104 }
105
106 declare_lint_pass!(Derive => [EXPL_IMPL_CLONE_ON_COPY, DERIVE_HASH_XOR_EQ, UNSAFE_DERIVE_DESERIALIZE]);
107
108 impl<'tcx> LateLintPass<'tcx> for Derive {
109     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
110         if let ItemKind::Impl {
111             of_trait: Some(ref trait_ref),
112             ..
113         } = item.kind
114         {
115             let ty = cx.tcx.type_of(cx.tcx.hir().local_def_id(item.hir_id));
116             let is_automatically_derived = is_automatically_derived(&*item.attrs);
117
118             check_hash_peq(cx, item.span, trait_ref, ty, is_automatically_derived);
119
120             if is_automatically_derived {
121                 check_unsafe_derive_deserialize(cx, item, trait_ref, ty);
122             } else {
123                 check_copy_clone(cx, item, trait_ref, ty);
124             }
125         }
126     }
127 }
128
129 /// Implementation of the `DERIVE_HASH_XOR_EQ` lint.
130 fn check_hash_peq<'tcx>(
131     cx: &LateContext<'tcx>,
132     span: Span,
133     trait_ref: &TraitRef<'_>,
134     ty: Ty<'tcx>,
135     hash_is_automatically_derived: bool,
136 ) {
137     if_chain! {
138         if match_path(&trait_ref.path, &paths::HASH);
139         if let Some(peq_trait_def_id) = cx.tcx.lang_items().eq_trait();
140         if let Some(def_id) = &trait_ref.trait_def_id();
141         if !def_id.is_local();
142         then {
143             // Look for the PartialEq implementations for `ty`
144             cx.tcx.for_each_relevant_impl(peq_trait_def_id, ty, |impl_id| {
145                 let peq_is_automatically_derived = is_automatically_derived(&cx.tcx.get_attrs(impl_id));
146
147                 if peq_is_automatically_derived == hash_is_automatically_derived {
148                     return;
149                 }
150
151                 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
152
153                 // Only care about `impl PartialEq<Foo> for Foo`
154                 // For `impl PartialEq<B> for A, input_types is [A, B]
155                 if trait_ref.substs.type_at(1) == ty {
156                     let mess = if peq_is_automatically_derived {
157                         "you are implementing `Hash` explicitly but have derived `PartialEq`"
158                     } else {
159                         "you are deriving `Hash` but have implemented `PartialEq` explicitly"
160                     };
161
162                     span_lint_and_then(
163                         cx,
164                         DERIVE_HASH_XOR_EQ,
165                         span,
166                         mess,
167                         |diag| {
168                             if let Some(local_def_id) = impl_id.as_local() {
169                                 let hir_id = cx.tcx.hir().as_local_hir_id(local_def_id);
170                                 diag.span_note(
171                                     cx.tcx.hir().span(hir_id),
172                                     "`PartialEq` implemented here"
173                                 );
174                             }
175                         }
176                     );
177                 }
178             });
179         }
180     }
181 }
182
183 /// Implementation of the `EXPL_IMPL_CLONE_ON_COPY` lint.
184 fn check_copy_clone<'tcx>(cx: &LateContext<'tcx>, item: &Item<'_>, trait_ref: &TraitRef<'_>, ty: Ty<'tcx>) {
185     if match_path(&trait_ref.path, &paths::CLONE_TRAIT) {
186         if !is_copy(cx, ty) {
187             return;
188         }
189
190         match ty.kind {
191             ty::Adt(def, _) if def.is_union() => return,
192
193             // Some types are not Clone by default but could be cloned “by hand” if necessary
194             ty::Adt(def, substs) => {
195                 for variant in &def.variants {
196                     for field in &variant.fields {
197                         if let ty::FnDef(..) = field.ty(cx.tcx, substs).kind {
198                             return;
199                         }
200                     }
201                     for subst in substs {
202                         if let ty::subst::GenericArgKind::Type(subst) = subst.unpack() {
203                             if let ty::Param(_) = subst.kind {
204                                 return;
205                             }
206                         }
207                     }
208                 }
209             },
210             _ => (),
211         }
212
213         span_lint_and_note(
214             cx,
215             EXPL_IMPL_CLONE_ON_COPY,
216             item.span,
217             "you are implementing `Clone` explicitly on a `Copy` type",
218             Some(item.span),
219             "consider deriving `Clone` or removing `Copy`",
220         );
221     }
222 }
223
224 /// Implementation of the `UNSAFE_DERIVE_DESERIALIZE` lint.
225 fn check_unsafe_derive_deserialize<'tcx>(
226     cx: &LateContext<'tcx>,
227     item: &Item<'_>,
228     trait_ref: &TraitRef<'_>,
229     ty: Ty<'tcx>,
230 ) {
231     fn item_from_def_id<'tcx>(cx: &LateContext<'tcx>, def_id: DefId) -> &'tcx Item<'tcx> {
232         let hir_id = cx.tcx.hir().as_local_hir_id(def_id.expect_local());
233         cx.tcx.hir().expect_item(hir_id)
234     }
235
236     fn has_unsafe<'tcx>(cx: &LateContext<'tcx>, item: &'tcx Item<'_>) -> bool {
237         let mut visitor = UnsafeVisitor { cx, has_unsafe: false };
238         walk_item(&mut visitor, item);
239         visitor.has_unsafe
240     }
241
242     if_chain! {
243         if match_path(&trait_ref.path, &paths::SERDE_DESERIALIZE);
244         if let ty::Adt(def, _) = ty.kind;
245         if def.did.is_local();
246         if cx.tcx.inherent_impls(def.did)
247             .iter()
248             .map(|imp_did| item_from_def_id(cx, *imp_did))
249             .any(|imp| has_unsafe(cx, imp));
250         then {
251             span_lint_and_help(
252                 cx,
253                 UNSAFE_DERIVE_DESERIALIZE,
254                 item.span,
255                 "you are deriving `serde::Deserialize` on a type that has methods using `unsafe`",
256                 None,
257                 "consider implementing `serde::Deserialize` manually. See https://serde.rs/impl-deserialize.html"
258             );
259         }
260     }
261 }
262
263 struct UnsafeVisitor<'a, 'tcx> {
264     cx: &'a LateContext<'tcx>,
265     has_unsafe: bool,
266 }
267
268 impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> {
269     type Map = Map<'tcx>;
270
271     fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: BodyId, span: Span, id: HirId) {
272         if self.has_unsafe {
273             return;
274         }
275
276         if_chain! {
277             if let Some(header) = kind.header();
278             if let Unsafety::Unsafe = header.unsafety;
279             then {
280                 self.has_unsafe = true;
281             }
282         }
283
284         walk_fn(self, kind, decl, body_id, span, id);
285     }
286
287     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
288         if self.has_unsafe {
289             return;
290         }
291
292         if let ExprKind::Block(block, _) = expr.kind {
293             match block.rules {
294                 BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided)
295                 | BlockCheckMode::PushUnsafeBlock(UnsafeSource::UserProvided)
296                 | BlockCheckMode::PopUnsafeBlock(UnsafeSource::UserProvided) => {
297                     self.has_unsafe = true;
298                 },
299                 _ => {},
300             }
301         }
302
303         walk_expr(self, expr);
304     }
305
306     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
307         NestedVisitorMap::All(self.cx.tcx.hir())
308     }
309 }