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