]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/derive.rs
Auto merge of #5493 - ebroto:unsafe_derive_deserialize, r=flip1995
[rust.git] / 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<'a, 'tcx> LateLintPass<'a, 'tcx> for Derive {
109     fn check_item(&mut self, cx: &LateContext<'a, '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<'a, 'tcx>(
131     cx: &LateContext<'a, '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, DERIVE_HASH_XOR_EQ, span,
164                         mess,
165                         |diag| {
166                         if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(impl_id) {
167                             diag.span_note(
168                                 cx.tcx.hir().span(hir_id),
169                                 "`PartialEq` implemented here"
170                             );
171                         }
172                     });
173                 }
174             });
175         }
176     }
177 }
178
179 /// Implementation of the `EXPL_IMPL_CLONE_ON_COPY` lint.
180 fn check_copy_clone<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, item: &Item<'_>, trait_ref: &TraitRef<'_>, ty: Ty<'tcx>) {
181     if match_path(&trait_ref.path, &paths::CLONE_TRAIT) {
182         if !is_copy(cx, ty) {
183             return;
184         }
185
186         match ty.kind {
187             ty::Adt(def, _) if def.is_union() => return,
188
189             // Some types are not Clone by default but could be cloned “by hand” if necessary
190             ty::Adt(def, substs) => {
191                 for variant in &def.variants {
192                     for field in &variant.fields {
193                         if let ty::FnDef(..) = field.ty(cx.tcx, substs).kind {
194                             return;
195                         }
196                     }
197                     for subst in substs {
198                         if let ty::subst::GenericArgKind::Type(subst) = subst.unpack() {
199                             if let ty::Param(_) = subst.kind {
200                                 return;
201                             }
202                         }
203                     }
204                 }
205             },
206             _ => (),
207         }
208
209         span_lint_and_note(
210             cx,
211             EXPL_IMPL_CLONE_ON_COPY,
212             item.span,
213             "you are implementing `Clone` explicitly on a `Copy` type",
214             Some(item.span),
215             "consider deriving `Clone` or removing `Copy`",
216         );
217     }
218 }
219
220 /// Implementation of the `UNSAFE_DERIVE_DESERIALIZE` lint.
221 fn check_unsafe_derive_deserialize<'a, 'tcx>(
222     cx: &LateContext<'a, 'tcx>,
223     item: &Item<'_>,
224     trait_ref: &TraitRef<'_>,
225     ty: Ty<'tcx>,
226 ) {
227     fn item_from_def_id<'tcx>(cx: &LateContext<'_, 'tcx>, def_id: DefId) -> &'tcx Item<'tcx> {
228         let hir_id = cx.tcx.hir().as_local_hir_id(def_id).unwrap();
229         cx.tcx.hir().expect_item(hir_id)
230     }
231
232     fn has_unsafe<'tcx>(cx: &LateContext<'_, 'tcx>, item: &'tcx Item<'_>) -> bool {
233         let mut visitor = UnsafeVisitor { cx, has_unsafe: false };
234         walk_item(&mut visitor, item);
235         visitor.has_unsafe
236     }
237
238     if_chain! {
239         if match_path(&trait_ref.path, &paths::SERDE_DESERIALIZE);
240         if let ty::Adt(def, _) = ty.kind;
241         if def.did.is_local();
242         if cx.tcx.inherent_impls(def.did)
243             .iter()
244             .map(|imp_did| item_from_def_id(cx, *imp_did))
245             .any(|imp| has_unsafe(cx, imp));
246         then {
247             span_lint_and_help(
248                 cx,
249                 UNSAFE_DERIVE_DESERIALIZE,
250                 item.span,
251                 "you are deriving `serde::Deserialize` on a type that has methods using `unsafe`",
252                 None,
253                 "consider implementing `serde::Deserialize` manually. See https://serde.rs/impl-deserialize.html"
254             );
255         }
256     }
257 }
258
259 struct UnsafeVisitor<'a, 'tcx> {
260     cx: &'a LateContext<'a, 'tcx>,
261     has_unsafe: bool,
262 }
263
264 impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> {
265     type Map = Map<'tcx>;
266
267     fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: BodyId, span: Span, id: HirId) {
268         if self.has_unsafe {
269             return;
270         }
271
272         if_chain! {
273             if let Some(header) = kind.header();
274             if let Unsafety::Unsafe = header.unsafety;
275             then {
276                 self.has_unsafe = true;
277             }
278         }
279
280         walk_fn(self, kind, decl, body_id, span, id);
281     }
282
283     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
284         if self.has_unsafe {
285             return;
286         }
287
288         if let ExprKind::Block(block, _) = expr.kind {
289             match block.rules {
290                 BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided)
291                 | BlockCheckMode::PushUnsafeBlock(UnsafeSource::UserProvided)
292                 | BlockCheckMode::PopUnsafeBlock(UnsafeSource::UserProvided) => {
293                     self.has_unsafe = true;
294                 },
295                 _ => {},
296             }
297         }
298
299         walk_expr(self, expr);
300     }
301
302     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
303         NestedVisitorMap::All(self.cx.tcx.hir())
304     }
305 }