]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/derive.rs
Update docs for `expl_impl_clone_on_copy`. Bug was fixed in 879fa5c9721c89c27be6a9db5...
[rust.git] / clippy_lints / src / derive.rs
1 use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_note, span_lint_and_then};
2 use clippy_utils::paths;
3 use clippy_utils::ty::{implements_trait, is_copy};
4 use clippy_utils::{get_trait_def_id, is_automatically_derived, is_lint_allowed, match_def_path};
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, Impl, 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
19     /// Checks for deriving `Hash` but implementing `PartialEq`
20     /// explicitly or vice versa.
21     ///
22     /// ### Why is this bad?
23     /// The implementation of these traits must agree (for
24     /// example for use with `HashMap`) so it’s probably a bad idea to use a
25     /// default-generated `Hash` implementation with an explicitly defined
26     /// `PartialEq`. In particular, the following must hold for any type:
27     ///
28     /// ```text
29     /// k1 == k2 ⇒ hash(k1) == hash(k2)
30     /// ```
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
48     /// Checks for deriving `Ord` but implementing `PartialOrd`
49     /// explicitly or vice versa.
50     ///
51     /// ### Why is this bad?
52     /// The implementation of these traits must agree (for
53     /// example for use with `sort`) so it’s probably a bad idea to use a
54     /// default-generated `Ord` implementation with an explicitly defined
55     /// `PartialOrd`. In particular, the following must hold for any type
56     /// implementing `Ord`:
57     ///
58     /// ```text
59     /// k1.cmp(&k2) == k1.partial_cmp(&k2).unwrap()
60     /// ```
61     ///
62     /// ### Example
63     /// ```rust,ignore
64     /// #[derive(Ord, PartialEq, Eq)]
65     /// struct Foo;
66     ///
67     /// impl PartialOrd for Foo {
68     ///     ...
69     /// }
70     /// ```
71     /// Use instead:
72     /// ```rust,ignore
73     /// #[derive(PartialEq, Eq)]
74     /// struct Foo;
75     ///
76     /// impl PartialOrd for Foo {
77     ///     fn partial_cmp(&self, other: &Foo) -> Option<Ordering> {
78     ///        Some(self.cmp(other))
79     ///     }
80     /// }
81     ///
82     /// impl Ord for Foo {
83     ///     ...
84     /// }
85     /// ```
86     /// or, if you don't need a custom ordering:
87     /// ```rust,ignore
88     /// #[derive(Ord, PartialOrd, PartialEq, Eq)]
89     /// struct Foo;
90     /// ```
91     pub DERIVE_ORD_XOR_PARTIAL_ORD,
92     correctness,
93     "deriving `Ord` but implementing `PartialOrd` explicitly"
94 }
95
96 declare_clippy_lint! {
97     /// ### What it does
98     /// Checks for explicit `Clone` implementations for `Copy`
99     /// types.
100     ///
101     /// ### Why is this bad?
102     /// To avoid surprising behaviour, these traits should
103     /// agree and the behaviour of `Copy` cannot be overridden. In almost all
104     /// situations a `Copy` type should have a `Clone` implementation that does
105     /// nothing more than copy the object, which is what `#[derive(Copy, Clone)]`
106     /// gets you.
107     ///
108     /// ### Example
109     /// ```rust,ignore
110     /// #[derive(Copy)]
111     /// struct Foo;
112     ///
113     /// impl Clone for Foo {
114     ///     // ..
115     /// }
116     /// ```
117     pub EXPL_IMPL_CLONE_ON_COPY,
118     pedantic,
119     "implementing `Clone` explicitly on `Copy` types"
120 }
121
122 declare_clippy_lint! {
123     /// ### What it does
124     /// Checks for deriving `serde::Deserialize` on a type that
125     /// has methods using `unsafe`.
126     ///
127     /// ### Why is this bad?
128     /// Deriving `serde::Deserialize` will create a constructor
129     /// that may violate invariants hold by another constructor.
130     ///
131     /// ### Example
132     /// ```rust,ignore
133     /// use serde::Deserialize;
134     ///
135     /// #[derive(Deserialize)]
136     /// pub struct Foo {
137     ///     // ..
138     /// }
139     ///
140     /// impl Foo {
141     ///     pub fn new() -> Self {
142     ///         // setup here ..
143     ///     }
144     ///
145     ///     pub unsafe fn parts() -> (&str, &str) {
146     ///         // assumes invariants hold
147     ///     }
148     /// }
149     /// ```
150     pub UNSAFE_DERIVE_DESERIALIZE,
151     pedantic,
152     "deriving `serde::Deserialize` on a type that has methods using `unsafe`"
153 }
154
155 declare_lint_pass!(Derive => [
156     EXPL_IMPL_CLONE_ON_COPY,
157     DERIVE_HASH_XOR_EQ,
158     DERIVE_ORD_XOR_PARTIAL_ORD,
159     UNSAFE_DERIVE_DESERIALIZE
160 ]);
161
162 impl<'tcx> LateLintPass<'tcx> for Derive {
163     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
164         if let ItemKind::Impl(Impl {
165             of_trait: Some(ref trait_ref),
166             ..
167         }) = item.kind
168         {
169             let ty = cx.tcx.type_of(item.def_id);
170             let attrs = cx.tcx.hir().attrs(item.hir_id());
171             let is_automatically_derived = is_automatically_derived(attrs);
172
173             check_hash_peq(cx, item.span, trait_ref, ty, is_automatically_derived);
174             check_ord_partial_ord(cx, item.span, trait_ref, ty, is_automatically_derived);
175
176             if is_automatically_derived {
177                 check_unsafe_derive_deserialize(cx, item, trait_ref, ty);
178             } else {
179                 check_copy_clone(cx, item, trait_ref, ty);
180             }
181         }
182     }
183 }
184
185 /// Implementation of the `DERIVE_HASH_XOR_EQ` lint.
186 fn check_hash_peq<'tcx>(
187     cx: &LateContext<'tcx>,
188     span: Span,
189     trait_ref: &TraitRef<'_>,
190     ty: Ty<'tcx>,
191     hash_is_automatically_derived: bool,
192 ) {
193     if_chain! {
194         if let Some(peq_trait_def_id) = cx.tcx.lang_items().eq_trait();
195         if let Some(def_id) = trait_ref.trait_def_id();
196         if match_def_path(cx, def_id, &paths::HASH);
197         then {
198             // Look for the PartialEq implementations for `ty`
199             cx.tcx.for_each_relevant_impl(peq_trait_def_id, ty, |impl_id| {
200                 let peq_is_automatically_derived = is_automatically_derived(cx.tcx.get_attrs(impl_id));
201
202                 if peq_is_automatically_derived == hash_is_automatically_derived {
203                     return;
204                 }
205
206                 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
207
208                 // Only care about `impl PartialEq<Foo> for Foo`
209                 // For `impl PartialEq<B> for A, input_types is [A, B]
210                 if trait_ref.substs.type_at(1) == ty {
211                     let mess = if peq_is_automatically_derived {
212                         "you are implementing `Hash` explicitly but have derived `PartialEq`"
213                     } else {
214                         "you are deriving `Hash` but have implemented `PartialEq` explicitly"
215                     };
216
217                     span_lint_and_then(
218                         cx,
219                         DERIVE_HASH_XOR_EQ,
220                         span,
221                         mess,
222                         |diag| {
223                             if let Some(local_def_id) = impl_id.as_local() {
224                                 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
225                                 diag.span_note(
226                                     cx.tcx.hir().span(hir_id),
227                                     "`PartialEq` implemented here"
228                                 );
229                             }
230                         }
231                     );
232                 }
233             });
234         }
235     }
236 }
237
238 /// Implementation of the `DERIVE_ORD_XOR_PARTIAL_ORD` lint.
239 fn check_ord_partial_ord<'tcx>(
240     cx: &LateContext<'tcx>,
241     span: Span,
242     trait_ref: &TraitRef<'_>,
243     ty: Ty<'tcx>,
244     ord_is_automatically_derived: bool,
245 ) {
246     if_chain! {
247         if let Some(ord_trait_def_id) = get_trait_def_id(cx, &paths::ORD);
248         if let Some(partial_ord_trait_def_id) = cx.tcx.lang_items().partial_ord_trait();
249         if let Some(def_id) = &trait_ref.trait_def_id();
250         if *def_id == ord_trait_def_id;
251         then {
252             // Look for the PartialOrd implementations for `ty`
253             cx.tcx.for_each_relevant_impl(partial_ord_trait_def_id, ty, |impl_id| {
254                 let partial_ord_is_automatically_derived = is_automatically_derived(cx.tcx.get_attrs(impl_id));
255
256                 if partial_ord_is_automatically_derived == ord_is_automatically_derived {
257                     return;
258                 }
259
260                 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
261
262                 // Only care about `impl PartialOrd<Foo> for Foo`
263                 // For `impl PartialOrd<B> for A, input_types is [A, B]
264                 if trait_ref.substs.type_at(1) == ty {
265                     let mess = if partial_ord_is_automatically_derived {
266                         "you are implementing `Ord` explicitly but have derived `PartialOrd`"
267                     } else {
268                         "you are deriving `Ord` but have implemented `PartialOrd` explicitly"
269                     };
270
271                     span_lint_and_then(
272                         cx,
273                         DERIVE_ORD_XOR_PARTIAL_ORD,
274                         span,
275                         mess,
276                         |diag| {
277                             if let Some(local_def_id) = impl_id.as_local() {
278                                 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
279                                 diag.span_note(
280                                     cx.tcx.hir().span(hir_id),
281                                     "`PartialOrd` implemented here"
282                                 );
283                             }
284                         }
285                     );
286                 }
287             });
288         }
289     }
290 }
291
292 /// Implementation of the `EXPL_IMPL_CLONE_ON_COPY` lint.
293 fn check_copy_clone<'tcx>(cx: &LateContext<'tcx>, item: &Item<'_>, trait_ref: &TraitRef<'_>, ty: Ty<'tcx>) {
294     let clone_id = match cx.tcx.lang_items().clone_trait() {
295         Some(id) if trait_ref.trait_def_id() == Some(id) => id,
296         _ => return,
297     };
298     let copy_id = match cx.tcx.lang_items().copy_trait() {
299         Some(id) => id,
300         None => return,
301     };
302     let (ty_adt, ty_subs) = match *ty.kind() {
303         // Unions can't derive clone.
304         ty::Adt(adt, subs) if !adt.is_union() => (adt, subs),
305         _ => return,
306     };
307     // If the current self type doesn't implement Copy (due to generic constraints), search to see if
308     // there's a Copy impl for any instance of the adt.
309     if !is_copy(cx, ty) {
310         if ty_subs.non_erasable_generics().next().is_some() {
311             let has_copy_impl = cx.tcx.all_local_trait_impls(()).get(&copy_id).map_or(false, |impls| {
312                 impls
313                     .iter()
314                     .any(|&id| matches!(cx.tcx.type_of(id).kind(), ty::Adt(adt, _) if ty_adt.did == adt.did))
315             });
316             if !has_copy_impl {
317                 return;
318             }
319         } else {
320             return;
321         }
322     }
323     // Derive constrains all generic types to requiring Clone. Check if any type is not constrained for
324     // this impl.
325     if ty_subs.types().any(|ty| !implements_trait(cx, ty, clone_id, &[])) {
326         return;
327     }
328
329     span_lint_and_note(
330         cx,
331         EXPL_IMPL_CLONE_ON_COPY,
332         item.span,
333         "you are implementing `Clone` explicitly on a `Copy` type",
334         Some(item.span),
335         "consider deriving `Clone` or removing `Copy`",
336     );
337 }
338
339 /// Implementation of the `UNSAFE_DERIVE_DESERIALIZE` lint.
340 fn check_unsafe_derive_deserialize<'tcx>(
341     cx: &LateContext<'tcx>,
342     item: &Item<'_>,
343     trait_ref: &TraitRef<'_>,
344     ty: Ty<'tcx>,
345 ) {
346     fn item_from_def_id<'tcx>(cx: &LateContext<'tcx>, def_id: DefId) -> &'tcx Item<'tcx> {
347         let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
348         cx.tcx.hir().expect_item(hir_id)
349     }
350
351     fn has_unsafe<'tcx>(cx: &LateContext<'tcx>, item: &'tcx Item<'_>) -> bool {
352         let mut visitor = UnsafeVisitor { cx, has_unsafe: false };
353         walk_item(&mut visitor, item);
354         visitor.has_unsafe
355     }
356
357     if_chain! {
358         if let Some(trait_def_id) = trait_ref.trait_def_id();
359         if match_def_path(cx, trait_def_id, &paths::SERDE_DESERIALIZE);
360         if let ty::Adt(def, _) = ty.kind();
361         if let Some(local_def_id) = def.did.as_local();
362         let adt_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
363         if !is_lint_allowed(cx, UNSAFE_DERIVE_DESERIALIZE, adt_hir_id);
364         if cx.tcx.inherent_impls(def.did)
365             .iter()
366             .map(|imp_did| item_from_def_id(cx, *imp_did))
367             .any(|imp| has_unsafe(cx, imp));
368         then {
369             span_lint_and_help(
370                 cx,
371                 UNSAFE_DERIVE_DESERIALIZE,
372                 item.span,
373                 "you are deriving `serde::Deserialize` on a type that has methods using `unsafe`",
374                 None,
375                 "consider implementing `serde::Deserialize` manually. See https://serde.rs/impl-deserialize.html"
376             );
377         }
378     }
379 }
380
381 struct UnsafeVisitor<'a, 'tcx> {
382     cx: &'a LateContext<'tcx>,
383     has_unsafe: bool,
384 }
385
386 impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> {
387     type Map = Map<'tcx>;
388
389     fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: BodyId, span: Span, id: HirId) {
390         if self.has_unsafe {
391             return;
392         }
393
394         if_chain! {
395             if let Some(header) = kind.header();
396             if let Unsafety::Unsafe = header.unsafety;
397             then {
398                 self.has_unsafe = true;
399             }
400         }
401
402         walk_fn(self, kind, decl, body_id, span, id);
403     }
404
405     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
406         if self.has_unsafe {
407             return;
408         }
409
410         if let ExprKind::Block(block, _) = expr.kind {
411             if let BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) = block.rules {
412                 self.has_unsafe = true;
413             }
414         }
415
416         walk_expr(self, expr);
417     }
418
419     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
420         NestedVisitorMap::All(self.cx.tcx.hir())
421     }
422 }