]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/derive.rs
Replace `&mut DiagnosticBuilder`, in signatures, with `&mut Diagnostic`.
[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, 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::nested_filter;
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     #[clippy::version = "pre 1.29.0"]
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     #[clippy::version = "1.47.0"]
92     pub DERIVE_ORD_XOR_PARTIAL_ORD,
93     correctness,
94     "deriving `Ord` but implementing `PartialOrd` explicitly"
95 }
96
97 declare_clippy_lint! {
98     /// ### What it does
99     /// Checks for explicit `Clone` implementations for `Copy`
100     /// types.
101     ///
102     /// ### Why is this bad?
103     /// 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     /// ### Example
110     /// ```rust,ignore
111     /// #[derive(Copy)]
112     /// struct Foo;
113     ///
114     /// impl Clone for Foo {
115     ///     // ..
116     /// }
117     /// ```
118     #[clippy::version = "pre 1.29.0"]
119     pub EXPL_IMPL_CLONE_ON_COPY,
120     pedantic,
121     "implementing `Clone` explicitly on `Copy` types"
122 }
123
124 declare_clippy_lint! {
125     /// ### What it does
126     /// Checks for deriving `serde::Deserialize` on a type that
127     /// has methods using `unsafe`.
128     ///
129     /// ### Why is this bad?
130     /// Deriving `serde::Deserialize` will create a constructor
131     /// that may violate invariants hold by another constructor.
132     ///
133     /// ### Example
134     /// ```rust,ignore
135     /// use serde::Deserialize;
136     ///
137     /// #[derive(Deserialize)]
138     /// pub struct Foo {
139     ///     // ..
140     /// }
141     ///
142     /// impl Foo {
143     ///     pub fn new() -> Self {
144     ///         // setup here ..
145     ///     }
146     ///
147     ///     pub unsafe fn parts() -> (&str, &str) {
148     ///         // assumes invariants hold
149     ///     }
150     /// }
151     /// ```
152     #[clippy::version = "1.45.0"]
153     pub UNSAFE_DERIVE_DESERIALIZE,
154     pedantic,
155     "deriving `serde::Deserialize` on a type that has methods using `unsafe`"
156 }
157
158 declare_lint_pass!(Derive => [
159     EXPL_IMPL_CLONE_ON_COPY,
160     DERIVE_HASH_XOR_EQ,
161     DERIVE_ORD_XOR_PARTIAL_ORD,
162     UNSAFE_DERIVE_DESERIALIZE
163 ]);
164
165 impl<'tcx> LateLintPass<'tcx> for Derive {
166     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
167         if let ItemKind::Impl(Impl {
168             of_trait: Some(ref trait_ref),
169             ..
170         }) = item.kind
171         {
172             let ty = cx.tcx.type_of(item.def_id);
173             let attrs = cx.tcx.hir().attrs(item.hir_id());
174             let is_automatically_derived = is_automatically_derived(attrs);
175
176             check_hash_peq(cx, item.span, trait_ref, ty, is_automatically_derived);
177             check_ord_partial_ord(cx, item.span, trait_ref, ty, is_automatically_derived);
178
179             if is_automatically_derived {
180                 check_unsafe_derive_deserialize(cx, item, trait_ref, ty);
181             } else {
182                 check_copy_clone(cx, item, trait_ref, ty);
183             }
184         }
185     }
186 }
187
188 /// Implementation of the `DERIVE_HASH_XOR_EQ` lint.
189 fn check_hash_peq<'tcx>(
190     cx: &LateContext<'tcx>,
191     span: Span,
192     trait_ref: &TraitRef<'_>,
193     ty: Ty<'tcx>,
194     hash_is_automatically_derived: bool,
195 ) {
196     if_chain! {
197         if let Some(peq_trait_def_id) = cx.tcx.lang_items().eq_trait();
198         if let Some(def_id) = trait_ref.trait_def_id();
199         if match_def_path(cx, def_id, &paths::HASH);
200         then {
201             // Look for the PartialEq implementations for `ty`
202             cx.tcx.for_each_relevant_impl(peq_trait_def_id, ty, |impl_id| {
203                 let peq_is_automatically_derived = is_automatically_derived(cx.tcx.get_attrs(impl_id));
204
205                 if peq_is_automatically_derived == hash_is_automatically_derived {
206                     return;
207                 }
208
209                 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
210
211                 // Only care about `impl PartialEq<Foo> for Foo`
212                 // For `impl PartialEq<B> for A, input_types is [A, B]
213                 if trait_ref.substs.type_at(1) == ty {
214                     let mess = if peq_is_automatically_derived {
215                         "you are implementing `Hash` explicitly but have derived `PartialEq`"
216                     } else {
217                         "you are deriving `Hash` but have implemented `PartialEq` explicitly"
218                     };
219
220                     span_lint_and_then(
221                         cx,
222                         DERIVE_HASH_XOR_EQ,
223                         span,
224                         mess,
225                         |diag| {
226                             if let Some(local_def_id) = impl_id.as_local() {
227                                 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
228                                 diag.span_note(
229                                     cx.tcx.hir().span(hir_id),
230                                     "`PartialEq` implemented here"
231                                 );
232                             }
233                         }
234                     );
235                 }
236             });
237         }
238     }
239 }
240
241 /// Implementation of the `DERIVE_ORD_XOR_PARTIAL_ORD` lint.
242 fn check_ord_partial_ord<'tcx>(
243     cx: &LateContext<'tcx>,
244     span: Span,
245     trait_ref: &TraitRef<'_>,
246     ty: Ty<'tcx>,
247     ord_is_automatically_derived: bool,
248 ) {
249     if_chain! {
250         if let Some(ord_trait_def_id) = get_trait_def_id(cx, &paths::ORD);
251         if let Some(partial_ord_trait_def_id) = cx.tcx.lang_items().partial_ord_trait();
252         if let Some(def_id) = &trait_ref.trait_def_id();
253         if *def_id == ord_trait_def_id;
254         then {
255             // Look for the PartialOrd implementations for `ty`
256             cx.tcx.for_each_relevant_impl(partial_ord_trait_def_id, ty, |impl_id| {
257                 let partial_ord_is_automatically_derived = is_automatically_derived(cx.tcx.get_attrs(impl_id));
258
259                 if partial_ord_is_automatically_derived == ord_is_automatically_derived {
260                     return;
261                 }
262
263                 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
264
265                 // Only care about `impl PartialOrd<Foo> for Foo`
266                 // For `impl PartialOrd<B> for A, input_types is [A, B]
267                 if trait_ref.substs.type_at(1) == ty {
268                     let mess = if partial_ord_is_automatically_derived {
269                         "you are implementing `Ord` explicitly but have derived `PartialOrd`"
270                     } else {
271                         "you are deriving `Ord` but have implemented `PartialOrd` explicitly"
272                     };
273
274                     span_lint_and_then(
275                         cx,
276                         DERIVE_ORD_XOR_PARTIAL_ORD,
277                         span,
278                         mess,
279                         |diag| {
280                             if let Some(local_def_id) = impl_id.as_local() {
281                                 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
282                                 diag.span_note(
283                                     cx.tcx.hir().span(hir_id),
284                                     "`PartialOrd` implemented here"
285                                 );
286                             }
287                         }
288                     );
289                 }
290             });
291         }
292     }
293 }
294
295 /// Implementation of the `EXPL_IMPL_CLONE_ON_COPY` lint.
296 fn check_copy_clone<'tcx>(cx: &LateContext<'tcx>, item: &Item<'_>, trait_ref: &TraitRef<'_>, ty: Ty<'tcx>) {
297     let clone_id = match cx.tcx.lang_items().clone_trait() {
298         Some(id) if trait_ref.trait_def_id() == Some(id) => id,
299         _ => return,
300     };
301     let copy_id = match cx.tcx.lang_items().copy_trait() {
302         Some(id) => id,
303         None => return,
304     };
305     let (ty_adt, ty_subs) = match *ty.kind() {
306         // Unions can't derive clone.
307         ty::Adt(adt, subs) if !adt.is_union() => (adt, subs),
308         _ => return,
309     };
310     // If the current self type doesn't implement Copy (due to generic constraints), search to see if
311     // there's a Copy impl for any instance of the adt.
312     if !is_copy(cx, ty) {
313         if ty_subs.non_erasable_generics().next().is_some() {
314             let has_copy_impl = cx.tcx.all_local_trait_impls(()).get(&copy_id).map_or(false, |impls| {
315                 impls
316                     .iter()
317                     .any(|&id| matches!(cx.tcx.type_of(id).kind(), ty::Adt(adt, _) if ty_adt.did == adt.did))
318             });
319             if !has_copy_impl {
320                 return;
321             }
322         } else {
323             return;
324         }
325     }
326     // Derive constrains all generic types to requiring Clone. Check if any type is not constrained for
327     // this impl.
328     if ty_subs.types().any(|ty| !implements_trait(cx, ty, clone_id, &[])) {
329         return;
330     }
331
332     span_lint_and_note(
333         cx,
334         EXPL_IMPL_CLONE_ON_COPY,
335         item.span,
336         "you are implementing `Clone` explicitly on a `Copy` type",
337         Some(item.span),
338         "consider deriving `Clone` or removing `Copy`",
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 has_unsafe<'tcx>(cx: &LateContext<'tcx>, item: &'tcx Item<'_>) -> bool {
350         let mut visitor = UnsafeVisitor { cx, has_unsafe: false };
351         walk_item(&mut visitor, item);
352         visitor.has_unsafe
353     }
354
355     if_chain! {
356         if let Some(trait_def_id) = trait_ref.trait_def_id();
357         if match_def_path(cx, trait_def_id, &paths::SERDE_DESERIALIZE);
358         if let ty::Adt(def, _) = ty.kind();
359         if let Some(local_def_id) = def.did.as_local();
360         let adt_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
361         if !is_lint_allowed(cx, UNSAFE_DERIVE_DESERIALIZE, adt_hir_id);
362         if cx.tcx.inherent_impls(def.did)
363             .iter()
364             .map(|imp_did| cx.tcx.hir().expect_item(imp_did.expect_local()))
365             .any(|imp| has_unsafe(cx, imp));
366         then {
367             span_lint_and_help(
368                 cx,
369                 UNSAFE_DERIVE_DESERIALIZE,
370                 item.span,
371                 "you are deriving `serde::Deserialize` on a type that has methods using `unsafe`",
372                 None,
373                 "consider implementing `serde::Deserialize` manually. See https://serde.rs/impl-deserialize.html"
374             );
375         }
376     }
377 }
378
379 struct UnsafeVisitor<'a, 'tcx> {
380     cx: &'a LateContext<'tcx>,
381     has_unsafe: bool,
382 }
383
384 impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> {
385     type NestedFilter = nested_filter::All;
386
387     fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: BodyId, span: Span, id: HirId) {
388         if self.has_unsafe {
389             return;
390         }
391
392         if_chain! {
393             if let Some(header) = kind.header();
394             if header.unsafety == Unsafety::Unsafe;
395             then {
396                 self.has_unsafe = true;
397             }
398         }
399
400         walk_fn(self, kind, decl, body_id, span, id);
401     }
402
403     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
404         if self.has_unsafe {
405             return;
406         }
407
408         if let ExprKind::Block(block, _) = expr.kind {
409             if block.rules == BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) {
410                 self.has_unsafe = true;
411             }
412         }
413
414         walk_expr(self, expr);
415     }
416
417     fn nested_visit_map(&mut self) -> Self::Map {
418         self.cx.tcx.hir()
419     }
420 }