]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/derive.rs
Rollup merge of #97415 - cjgillot:is-late-bound-solo, r=estebank
[rust.git] / clippy_lints / src / derive.rs
1 use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_note, span_lint_and_sugg, span_lint_and_then};
2 use clippy_utils::paths;
3 use clippy_utils::ty::{implements_trait, is_copy};
4 use clippy_utils::{is_lint_allowed, match_def_path};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::intravisit::{walk_expr, walk_fn, walk_item, FnKind, 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::nested_filter;
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 use rustc_span::sym;
17
18 declare_clippy_lint! {
19     /// ### What it does
20     /// Checks for deriving `Hash` but implementing `PartialEq`
21     /// explicitly or vice versa.
22     ///
23     /// ### Why is this bad?
24     /// The implementation of these traits must agree (for
25     /// example for use with `HashMap`) so it’s probably a bad idea to use a
26     /// default-generated `Hash` implementation with an explicitly defined
27     /// `PartialEq`. In particular, the following must hold for any type:
28     ///
29     /// ```text
30     /// k1 == k2 ⇒ hash(k1) == hash(k2)
31     /// ```
32     ///
33     /// ### Example
34     /// ```ignore
35     /// #[derive(Hash)]
36     /// struct Foo;
37     ///
38     /// impl PartialEq for Foo {
39     ///     ...
40     /// }
41     /// ```
42     #[clippy::version = "pre 1.29.0"]
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
50     /// Checks for deriving `Ord` but implementing `PartialOrd`
51     /// explicitly or vice versa.
52     ///
53     /// ### Why is this bad?
54     /// The implementation of these traits must agree (for
55     /// example for use with `sort`) so it’s probably a bad idea to use a
56     /// default-generated `Ord` implementation with an explicitly defined
57     /// `PartialOrd`. In particular, the following must hold for any type
58     /// implementing `Ord`:
59     ///
60     /// ```text
61     /// k1.cmp(&k2) == k1.partial_cmp(&k2).unwrap()
62     /// ```
63     ///
64     /// ### Example
65     /// ```rust,ignore
66     /// #[derive(Ord, PartialEq, Eq)]
67     /// struct Foo;
68     ///
69     /// impl PartialOrd for Foo {
70     ///     ...
71     /// }
72     /// ```
73     /// Use instead:
74     /// ```rust,ignore
75     /// #[derive(PartialEq, Eq)]
76     /// struct Foo;
77     ///
78     /// impl PartialOrd for Foo {
79     ///     fn partial_cmp(&self, other: &Foo) -> Option<Ordering> {
80     ///        Some(self.cmp(other))
81     ///     }
82     /// }
83     ///
84     /// impl Ord for Foo {
85     ///     ...
86     /// }
87     /// ```
88     /// or, if you don't need a custom ordering:
89     /// ```rust,ignore
90     /// #[derive(Ord, PartialOrd, PartialEq, Eq)]
91     /// struct Foo;
92     /// ```
93     #[clippy::version = "1.47.0"]
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
101     /// Checks for explicit `Clone` implementations for `Copy`
102     /// types.
103     ///
104     /// ### Why is this bad?
105     /// To avoid surprising behavior, these traits should
106     /// agree and the behavior of `Copy` cannot be overridden. In almost all
107     /// situations a `Copy` type should have a `Clone` implementation that does
108     /// nothing more than copy the object, which is what `#[derive(Copy, Clone)]`
109     /// gets you.
110     ///
111     /// ### Example
112     /// ```rust,ignore
113     /// #[derive(Copy)]
114     /// struct Foo;
115     ///
116     /// impl Clone for Foo {
117     ///     // ..
118     /// }
119     /// ```
120     #[clippy::version = "pre 1.29.0"]
121     pub EXPL_IMPL_CLONE_ON_COPY,
122     pedantic,
123     "implementing `Clone` explicitly on `Copy` types"
124 }
125
126 declare_clippy_lint! {
127     /// ### What it does
128     /// Checks for deriving `serde::Deserialize` on a type that
129     /// has methods using `unsafe`.
130     ///
131     /// ### Why is this bad?
132     /// Deriving `serde::Deserialize` will create a constructor
133     /// that may violate invariants hold by another constructor.
134     ///
135     /// ### Example
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     #[clippy::version = "1.45.0"]
155     pub UNSAFE_DERIVE_DESERIALIZE,
156     pedantic,
157     "deriving `serde::Deserialize` on a type that has methods using `unsafe`"
158 }
159
160 declare_clippy_lint! {
161     /// ### What it does
162     /// Checks for types that derive `PartialEq` and could implement `Eq`.
163     ///
164     /// ### Why is this bad?
165     /// If a type `T` derives `PartialEq` and all of its members implement `Eq`,
166     /// then `T` can always implement `Eq`. Implementing `Eq` allows `T` to be used
167     /// in APIs that require `Eq` types. It also allows structs containing `T` to derive
168     /// `Eq` themselves.
169     ///
170     /// ### Example
171     /// ```rust
172     /// #[derive(PartialEq)]
173     /// struct Foo {
174     ///     i_am_eq: i32,
175     ///     i_am_eq_too: Vec<String>,
176     /// }
177     /// ```
178     /// Use instead:
179     /// ```rust
180     /// #[derive(PartialEq, Eq)]
181     /// struct Foo {
182     ///     i_am_eq: i32,
183     ///     i_am_eq_too: Vec<String>,
184     /// }
185     /// ```
186     #[clippy::version = "1.62.0"]
187     pub DERIVE_PARTIAL_EQ_WITHOUT_EQ,
188     style,
189     "deriving `PartialEq` on a type that can implement `Eq`, without implementing `Eq`"
190 }
191
192 declare_lint_pass!(Derive => [
193     EXPL_IMPL_CLONE_ON_COPY,
194     DERIVE_HASH_XOR_EQ,
195     DERIVE_ORD_XOR_PARTIAL_ORD,
196     UNSAFE_DERIVE_DESERIALIZE,
197     DERIVE_PARTIAL_EQ_WITHOUT_EQ
198 ]);
199
200 impl<'tcx> LateLintPass<'tcx> for Derive {
201     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
202         if let ItemKind::Impl(Impl {
203             of_trait: Some(ref trait_ref),
204             ..
205         }) = item.kind
206         {
207             let ty = cx.tcx.type_of(item.def_id);
208             let is_automatically_derived = cx.tcx.has_attr(item.def_id.to_def_id(), sym::automatically_derived);
209
210             check_hash_peq(cx, item.span, trait_ref, ty, is_automatically_derived);
211             check_ord_partial_ord(cx, item.span, trait_ref, ty, is_automatically_derived);
212
213             if is_automatically_derived {
214                 check_unsafe_derive_deserialize(cx, item, trait_ref, ty);
215                 check_partial_eq_without_eq(cx, item.span, trait_ref, ty);
216             } else {
217                 check_copy_clone(cx, item, trait_ref, ty);
218             }
219         }
220     }
221 }
222
223 /// Implementation of the `DERIVE_HASH_XOR_EQ` lint.
224 fn check_hash_peq<'tcx>(
225     cx: &LateContext<'tcx>,
226     span: Span,
227     trait_ref: &TraitRef<'_>,
228     ty: Ty<'tcx>,
229     hash_is_automatically_derived: bool,
230 ) {
231     if_chain! {
232         if let Some(peq_trait_def_id) = cx.tcx.lang_items().eq_trait();
233         if let Some(def_id) = trait_ref.trait_def_id();
234         if cx.tcx.is_diagnostic_item(sym::Hash, def_id);
235         then {
236             // Look for the PartialEq implementations for `ty`
237             cx.tcx.for_each_relevant_impl(peq_trait_def_id, ty, |impl_id| {
238                 let peq_is_automatically_derived = cx.tcx.has_attr(impl_id, sym::automatically_derived);
239
240                 if peq_is_automatically_derived == hash_is_automatically_derived {
241                     return;
242                 }
243
244                 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
245
246                 // Only care about `impl PartialEq<Foo> for Foo`
247                 // For `impl PartialEq<B> for A, input_types is [A, B]
248                 if trait_ref.substs.type_at(1) == ty {
249                     let mess = if peq_is_automatically_derived {
250                         "you are implementing `Hash` explicitly but have derived `PartialEq`"
251                     } else {
252                         "you are deriving `Hash` but have implemented `PartialEq` explicitly"
253                     };
254
255                     span_lint_and_then(
256                         cx,
257                         DERIVE_HASH_XOR_EQ,
258                         span,
259                         mess,
260                         |diag| {
261                             if let Some(local_def_id) = impl_id.as_local() {
262                                 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
263                                 diag.span_note(
264                                     cx.tcx.hir().span(hir_id),
265                                     "`PartialEq` implemented here"
266                                 );
267                             }
268                         }
269                     );
270                 }
271             });
272         }
273     }
274 }
275
276 /// Implementation of the `DERIVE_ORD_XOR_PARTIAL_ORD` lint.
277 fn check_ord_partial_ord<'tcx>(
278     cx: &LateContext<'tcx>,
279     span: Span,
280     trait_ref: &TraitRef<'_>,
281     ty: Ty<'tcx>,
282     ord_is_automatically_derived: bool,
283 ) {
284     if_chain! {
285         if let Some(ord_trait_def_id) = cx.tcx.get_diagnostic_item(sym::Ord);
286         if let Some(partial_ord_trait_def_id) = cx.tcx.lang_items().partial_ord_trait();
287         if let Some(def_id) = &trait_ref.trait_def_id();
288         if *def_id == ord_trait_def_id;
289         then {
290             // Look for the PartialOrd implementations for `ty`
291             cx.tcx.for_each_relevant_impl(partial_ord_trait_def_id, ty, |impl_id| {
292                 let partial_ord_is_automatically_derived = cx.tcx.has_attr(impl_id, sym::automatically_derived);
293
294                 if partial_ord_is_automatically_derived == ord_is_automatically_derived {
295                     return;
296                 }
297
298                 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
299
300                 // Only care about `impl PartialOrd<Foo> for Foo`
301                 // For `impl PartialOrd<B> for A, input_types is [A, B]
302                 if trait_ref.substs.type_at(1) == ty {
303                     let mess = if partial_ord_is_automatically_derived {
304                         "you are implementing `Ord` explicitly but have derived `PartialOrd`"
305                     } else {
306                         "you are deriving `Ord` but have implemented `PartialOrd` explicitly"
307                     };
308
309                     span_lint_and_then(
310                         cx,
311                         DERIVE_ORD_XOR_PARTIAL_ORD,
312                         span,
313                         mess,
314                         |diag| {
315                             if let Some(local_def_id) = impl_id.as_local() {
316                                 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
317                                 diag.span_note(
318                                     cx.tcx.hir().span(hir_id),
319                                     "`PartialOrd` implemented here"
320                                 );
321                             }
322                         }
323                     );
324                 }
325             });
326         }
327     }
328 }
329
330 /// Implementation of the `EXPL_IMPL_CLONE_ON_COPY` lint.
331 fn check_copy_clone<'tcx>(cx: &LateContext<'tcx>, item: &Item<'_>, trait_ref: &TraitRef<'_>, ty: Ty<'tcx>) {
332     let clone_id = match cx.tcx.lang_items().clone_trait() {
333         Some(id) if trait_ref.trait_def_id() == Some(id) => id,
334         _ => return,
335     };
336     let copy_id = match cx.tcx.lang_items().copy_trait() {
337         Some(id) => id,
338         None => return,
339     };
340     let (ty_adt, ty_subs) = match *ty.kind() {
341         // Unions can't derive clone.
342         ty::Adt(adt, subs) if !adt.is_union() => (adt, subs),
343         _ => return,
344     };
345     // If the current self type doesn't implement Copy (due to generic constraints), search to see if
346     // there's a Copy impl for any instance of the adt.
347     if !is_copy(cx, ty) {
348         if ty_subs.non_erasable_generics().next().is_some() {
349             let has_copy_impl = cx.tcx.all_local_trait_impls(()).get(&copy_id).map_or(false, |impls| {
350                 impls
351                     .iter()
352                     .any(|&id| matches!(cx.tcx.type_of(id).kind(), ty::Adt(adt, _) if ty_adt.did() == adt.did()))
353             });
354             if !has_copy_impl {
355                 return;
356             }
357         } else {
358             return;
359         }
360     }
361     // Derive constrains all generic types to requiring Clone. Check if any type is not constrained for
362     // this impl.
363     if ty_subs.types().any(|ty| !implements_trait(cx, ty, clone_id, &[])) {
364         return;
365     }
366
367     span_lint_and_note(
368         cx,
369         EXPL_IMPL_CLONE_ON_COPY,
370         item.span,
371         "you are implementing `Clone` explicitly on a `Copy` type",
372         Some(item.span),
373         "consider deriving `Clone` or removing `Copy`",
374     );
375 }
376
377 /// Implementation of the `UNSAFE_DERIVE_DESERIALIZE` lint.
378 fn check_unsafe_derive_deserialize<'tcx>(
379     cx: &LateContext<'tcx>,
380     item: &Item<'_>,
381     trait_ref: &TraitRef<'_>,
382     ty: Ty<'tcx>,
383 ) {
384     fn has_unsafe<'tcx>(cx: &LateContext<'tcx>, item: &'tcx Item<'_>) -> bool {
385         let mut visitor = UnsafeVisitor { cx, has_unsafe: false };
386         walk_item(&mut visitor, item);
387         visitor.has_unsafe
388     }
389
390     if_chain! {
391         if let Some(trait_def_id) = trait_ref.trait_def_id();
392         if match_def_path(cx, trait_def_id, &paths::SERDE_DESERIALIZE);
393         if let ty::Adt(def, _) = ty.kind();
394         if let Some(local_def_id) = def.did().as_local();
395         let adt_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
396         if !is_lint_allowed(cx, UNSAFE_DERIVE_DESERIALIZE, adt_hir_id);
397         if cx.tcx.inherent_impls(def.did())
398             .iter()
399             .map(|imp_did| cx.tcx.hir().expect_item(imp_did.expect_local()))
400             .any(|imp| has_unsafe(cx, imp));
401         then {
402             span_lint_and_help(
403                 cx,
404                 UNSAFE_DERIVE_DESERIALIZE,
405                 item.span,
406                 "you are deriving `serde::Deserialize` on a type that has methods using `unsafe`",
407                 None,
408                 "consider implementing `serde::Deserialize` manually. See https://serde.rs/impl-deserialize.html"
409             );
410         }
411     }
412 }
413
414 struct UnsafeVisitor<'a, 'tcx> {
415     cx: &'a LateContext<'tcx>,
416     has_unsafe: bool,
417 }
418
419 impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> {
420     type NestedFilter = nested_filter::All;
421
422     fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: BodyId, span: Span, id: HirId) {
423         if self.has_unsafe {
424             return;
425         }
426
427         if_chain! {
428             if let Some(header) = kind.header();
429             if header.unsafety == Unsafety::Unsafe;
430             then {
431                 self.has_unsafe = true;
432             }
433         }
434
435         walk_fn(self, kind, decl, body_id, span, id);
436     }
437
438     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
439         if self.has_unsafe {
440             return;
441         }
442
443         if let ExprKind::Block(block, _) = expr.kind {
444             if block.rules == BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) {
445                 self.has_unsafe = true;
446             }
447         }
448
449         walk_expr(self, expr);
450     }
451
452     fn nested_visit_map(&mut self) -> Self::Map {
453         self.cx.tcx.hir()
454     }
455 }
456
457 /// Implementation of the `DERIVE_PARTIAL_EQ_WITHOUT_EQ` lint.
458 fn check_partial_eq_without_eq<'tcx>(cx: &LateContext<'tcx>, span: Span, trait_ref: &TraitRef<'_>, ty: Ty<'tcx>) {
459     if_chain! {
460         if let ty::Adt(adt, substs) = ty.kind();
461         if let Some(eq_trait_def_id) = cx.tcx.get_diagnostic_item(sym::Eq);
462         if let Some(def_id) = trait_ref.trait_def_id();
463         if cx.tcx.is_diagnostic_item(sym::PartialEq, def_id);
464         if !implements_trait(cx, ty, eq_trait_def_id, substs);
465         then {
466             // If all of our fields implement `Eq`, we can implement `Eq` too
467             for variant in adt.variants() {
468                 for field in &variant.fields {
469                     let ty = field.ty(cx.tcx, substs);
470
471                     if !implements_trait(cx, ty, eq_trait_def_id, substs) {
472                         return;
473                     }
474                 }
475             }
476
477             span_lint_and_sugg(
478                 cx,
479                 DERIVE_PARTIAL_EQ_WITHOUT_EQ,
480                 span.ctxt().outer_expn_data().call_site,
481                 "you are deriving `PartialEq` and can implement `Eq`",
482                 "consider deriving `Eq` as well",
483                 "PartialEq, Eq".to_string(),
484                 Applicability::MachineApplicable,
485             )
486         }
487     }
488 }