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