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