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::def_id::DefId;
8 use rustc_hir::intravisit::{walk_expr, walk_fn, walk_item, FnKind, Visitor};
10 self as hir, BlockCheckMode, BodyId, Constness, Expr, ExprKind, FnDecl, HirId, Impl, Item, ItemKind, UnsafeSource,
13 use rustc_lint::{LateContext, LateLintPass};
14 use rustc_middle::hir::nested_filter;
15 use rustc_middle::traits::Reveal;
16 use rustc_middle::ty::{
17 self, Binder, BoundConstness, Clause, GenericParamDefKind, ImplPolarity, ParamEnv, PredicateKind, TraitPredicate,
20 use rustc_session::{declare_lint_pass, declare_tool_lint};
21 use rustc_span::source_map::Span;
24 declare_clippy_lint! {
26 /// Checks for deriving `Hash` but implementing `PartialEq`
27 /// explicitly or vice versa.
29 /// ### Why is this bad?
30 /// The implementation of these traits must agree (for
31 /// example for use with `HashMap`) so it’s probably a bad idea to use a
32 /// default-generated `Hash` implementation with an explicitly defined
33 /// `PartialEq`. In particular, the following must hold for any type:
36 /// k1 == k2 ⇒ hash(k1) == hash(k2)
44 /// impl PartialEq for Foo {
48 #[clippy::version = "pre 1.29.0"]
49 pub DERIVE_HASH_XOR_EQ,
51 "deriving `Hash` but implementing `PartialEq` explicitly"
54 declare_clippy_lint! {
56 /// Checks for deriving `Ord` but implementing `PartialOrd`
57 /// explicitly or vice versa.
59 /// ### Why is this bad?
60 /// The implementation of these traits must agree (for
61 /// example for use with `sort`) so it’s probably a bad idea to use a
62 /// default-generated `Ord` implementation with an explicitly defined
63 /// `PartialOrd`. In particular, the following must hold for any type
64 /// implementing `Ord`:
67 /// k1.cmp(&k2) == k1.partial_cmp(&k2).unwrap()
72 /// #[derive(Ord, PartialEq, Eq)]
75 /// impl PartialOrd for Foo {
81 /// #[derive(PartialEq, Eq)]
84 /// impl PartialOrd for Foo {
85 /// fn partial_cmp(&self, other: &Foo) -> Option<Ordering> {
86 /// Some(self.cmp(other))
90 /// impl Ord for Foo {
94 /// or, if you don't need a custom ordering:
96 /// #[derive(Ord, PartialOrd, PartialEq, Eq)]
99 #[clippy::version = "1.47.0"]
100 pub DERIVE_ORD_XOR_PARTIAL_ORD,
102 "deriving `Ord` but implementing `PartialOrd` explicitly"
105 declare_clippy_lint! {
107 /// Checks for explicit `Clone` implementations for `Copy`
110 /// ### Why is this bad?
111 /// To avoid surprising behavior, these traits should
112 /// agree and the behavior of `Copy` cannot be overridden. In almost all
113 /// situations a `Copy` type should have a `Clone` implementation that does
114 /// nothing more than copy the object, which is what `#[derive(Copy, Clone)]`
122 /// impl Clone for Foo {
126 #[clippy::version = "pre 1.29.0"]
127 pub EXPL_IMPL_CLONE_ON_COPY,
129 "implementing `Clone` explicitly on `Copy` types"
132 declare_clippy_lint! {
134 /// Checks for deriving `serde::Deserialize` on a type that
135 /// has methods using `unsafe`.
137 /// ### Why is this bad?
138 /// Deriving `serde::Deserialize` will create a constructor
139 /// that may violate invariants hold by another constructor.
143 /// use serde::Deserialize;
145 /// #[derive(Deserialize)]
151 /// pub fn new() -> Self {
155 /// pub unsafe fn parts() -> (&str, &str) {
156 /// // assumes invariants hold
160 #[clippy::version = "1.45.0"]
161 pub UNSAFE_DERIVE_DESERIALIZE,
163 "deriving `serde::Deserialize` on a type that has methods using `unsafe`"
166 declare_clippy_lint! {
168 /// Checks for types that derive `PartialEq` and could implement `Eq`.
170 /// ### Why is this bad?
171 /// If a type `T` derives `PartialEq` and all of its members implement `Eq`,
172 /// then `T` can always implement `Eq`. Implementing `Eq` allows `T` to be used
173 /// in APIs that require `Eq` types. It also allows structs containing `T` to derive
178 /// #[derive(PartialEq)]
181 /// i_am_eq_too: Vec<String>,
186 /// #[derive(PartialEq, Eq)]
189 /// i_am_eq_too: Vec<String>,
192 #[clippy::version = "1.63.0"]
193 pub DERIVE_PARTIAL_EQ_WITHOUT_EQ,
195 "deriving `PartialEq` on a type that can implement `Eq`, without implementing `Eq`"
198 declare_lint_pass!(Derive => [
199 EXPL_IMPL_CLONE_ON_COPY,
201 DERIVE_ORD_XOR_PARTIAL_ORD,
202 UNSAFE_DERIVE_DESERIALIZE,
203 DERIVE_PARTIAL_EQ_WITHOUT_EQ
206 impl<'tcx> LateLintPass<'tcx> for Derive {
207 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
208 if let ItemKind::Impl(Impl {
209 of_trait: Some(ref trait_ref),
213 let ty = cx.tcx.type_of(item.owner_id);
214 let is_automatically_derived = cx.tcx.has_attr(item.owner_id.to_def_id(), sym::automatically_derived);
216 check_hash_peq(cx, item.span, trait_ref, ty, is_automatically_derived);
217 check_ord_partial_ord(cx, item.span, trait_ref, ty, is_automatically_derived);
219 if is_automatically_derived {
220 check_unsafe_derive_deserialize(cx, item, trait_ref, ty);
221 check_partial_eq_without_eq(cx, item.span, trait_ref, ty);
223 check_copy_clone(cx, item, trait_ref, ty);
229 /// Implementation of the `DERIVE_HASH_XOR_EQ` lint.
230 fn check_hash_peq<'tcx>(
231 cx: &LateContext<'tcx>,
233 trait_ref: &hir::TraitRef<'_>,
235 hash_is_automatically_derived: bool,
238 if let Some(peq_trait_def_id) = cx.tcx.lang_items().eq_trait();
239 if let Some(def_id) = trait_ref.trait_def_id();
240 if cx.tcx.is_diagnostic_item(sym::Hash, def_id);
242 // Look for the PartialEq implementations for `ty`
243 cx.tcx.for_each_relevant_impl(peq_trait_def_id, ty, |impl_id| {
244 let peq_is_automatically_derived = cx.tcx.has_attr(impl_id, sym::automatically_derived);
246 if peq_is_automatically_derived == hash_is_automatically_derived {
250 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
252 // Only care about `impl PartialEq<Foo> for Foo`
253 // For `impl PartialEq<B> for A, input_types is [A, B]
254 if trait_ref.substs.type_at(1) == ty {
255 let mess = if peq_is_automatically_derived {
256 "you are implementing `Hash` explicitly but have derived `PartialEq`"
258 "you are deriving `Hash` but have implemented `PartialEq` explicitly"
267 if let Some(local_def_id) = impl_id.as_local() {
268 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
270 cx.tcx.hir().span(hir_id),
271 "`PartialEq` implemented here"
282 /// Implementation of the `DERIVE_ORD_XOR_PARTIAL_ORD` lint.
283 fn check_ord_partial_ord<'tcx>(
284 cx: &LateContext<'tcx>,
286 trait_ref: &hir::TraitRef<'_>,
288 ord_is_automatically_derived: bool,
291 if let Some(ord_trait_def_id) = cx.tcx.get_diagnostic_item(sym::Ord);
292 if let Some(partial_ord_trait_def_id) = cx.tcx.lang_items().partial_ord_trait();
293 if let Some(def_id) = &trait_ref.trait_def_id();
294 if *def_id == ord_trait_def_id;
296 // Look for the PartialOrd implementations for `ty`
297 cx.tcx.for_each_relevant_impl(partial_ord_trait_def_id, ty, |impl_id| {
298 let partial_ord_is_automatically_derived = cx.tcx.has_attr(impl_id, sym::automatically_derived);
300 if partial_ord_is_automatically_derived == ord_is_automatically_derived {
304 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
306 // Only care about `impl PartialOrd<Foo> for Foo`
307 // For `impl PartialOrd<B> for A, input_types is [A, B]
308 if trait_ref.substs.type_at(1) == ty {
309 let mess = if partial_ord_is_automatically_derived {
310 "you are implementing `Ord` explicitly but have derived `PartialOrd`"
312 "you are deriving `Ord` but have implemented `PartialOrd` explicitly"
317 DERIVE_ORD_XOR_PARTIAL_ORD,
321 if let Some(local_def_id) = impl_id.as_local() {
322 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
324 cx.tcx.hir().span(hir_id),
325 "`PartialOrd` implemented here"
336 /// Implementation of the `EXPL_IMPL_CLONE_ON_COPY` lint.
337 fn check_copy_clone<'tcx>(cx: &LateContext<'tcx>, item: &Item<'_>, trait_ref: &hir::TraitRef<'_>, ty: Ty<'tcx>) {
338 let clone_id = match cx.tcx.lang_items().clone_trait() {
339 Some(id) if trait_ref.trait_def_id() == Some(id) => id,
342 let Some(copy_id) = cx.tcx.lang_items().copy_trait() else { return };
343 let (ty_adt, ty_subs) = match *ty.kind() {
344 // Unions can't derive clone.
345 ty::Adt(adt, subs) if !adt.is_union() => (adt, subs),
348 // If the current self type doesn't implement Copy (due to generic constraints), search to see if
349 // there's a Copy impl for any instance of the adt.
350 if !is_copy(cx, ty) {
351 if ty_subs.non_erasable_generics().next().is_some() {
352 let has_copy_impl = cx.tcx.all_local_trait_impls(()).get(©_id).map_or(false, |impls| {
355 .any(|&id| matches!(cx.tcx.type_of(id).kind(), ty::Adt(adt, _) if ty_adt.did() == adt.did()))
364 // Derive constrains all generic types to requiring Clone. Check if any type is not constrained for
366 if ty_subs.types().any(|ty| !implements_trait(cx, ty, clone_id, &[])) {
372 EXPL_IMPL_CLONE_ON_COPY,
374 "you are implementing `Clone` explicitly on a `Copy` type",
376 "consider deriving `Clone` or removing `Copy`",
380 /// Implementation of the `UNSAFE_DERIVE_DESERIALIZE` lint.
381 fn check_unsafe_derive_deserialize<'tcx>(
382 cx: &LateContext<'tcx>,
384 trait_ref: &hir::TraitRef<'_>,
387 fn has_unsafe<'tcx>(cx: &LateContext<'tcx>, item: &'tcx Item<'_>) -> bool {
388 let mut visitor = UnsafeVisitor { cx, has_unsafe: false };
389 walk_item(&mut visitor, item);
394 if let Some(trait_def_id) = trait_ref.trait_def_id();
395 if match_def_path(cx, trait_def_id, &paths::SERDE_DESERIALIZE);
396 if let ty::Adt(def, _) = ty.kind();
397 if let Some(local_def_id) = def.did().as_local();
398 let adt_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
399 if !is_lint_allowed(cx, UNSAFE_DERIVE_DESERIALIZE, adt_hir_id);
400 if cx.tcx.inherent_impls(def.did())
402 .map(|imp_did| cx.tcx.hir().expect_item(imp_did.expect_local()))
403 .any(|imp| has_unsafe(cx, imp));
407 UNSAFE_DERIVE_DESERIALIZE,
409 "you are deriving `serde::Deserialize` on a type that has methods using `unsafe`",
411 "consider implementing `serde::Deserialize` manually. See https://serde.rs/impl-deserialize.html"
417 struct UnsafeVisitor<'a, 'tcx> {
418 cx: &'a LateContext<'tcx>,
422 impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> {
423 type NestedFilter = nested_filter::All;
425 fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: BodyId, _: Span, id: HirId) {
431 if let Some(header) = kind.header();
432 if header.unsafety == Unsafety::Unsafe;
434 self.has_unsafe = true;
438 walk_fn(self, kind, decl, body_id, id);
441 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
446 if let ExprKind::Block(block, _) = expr.kind {
447 if block.rules == BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) {
448 self.has_unsafe = true;
452 walk_expr(self, expr);
455 fn nested_visit_map(&mut self) -> Self::Map {
460 /// Implementation of the `DERIVE_PARTIAL_EQ_WITHOUT_EQ` lint.
461 fn check_partial_eq_without_eq<'tcx>(cx: &LateContext<'tcx>, span: Span, trait_ref: &hir::TraitRef<'_>, ty: Ty<'tcx>) {
463 if let ty::Adt(adt, substs) = ty.kind();
464 if cx.tcx.visibility(adt.did()).is_public();
465 if let Some(eq_trait_def_id) = cx.tcx.get_diagnostic_item(sym::Eq);
466 if let Some(def_id) = trait_ref.trait_def_id();
467 if cx.tcx.is_diagnostic_item(sym::PartialEq, def_id);
468 let param_env = param_env_for_derived_eq(cx.tcx, adt.did(), eq_trait_def_id);
469 if !implements_trait_with_env(cx.tcx, param_env, ty, eq_trait_def_id, []);
470 // If all of our fields implement `Eq`, we can implement `Eq` too
473 .map(|f| f.ty(cx.tcx, substs))
474 .all(|ty| implements_trait_with_env(cx.tcx, param_env, ty, eq_trait_def_id, []));
478 DERIVE_PARTIAL_EQ_WITHOUT_EQ,
479 span.ctxt().outer_expn_data().call_site,
480 "you are deriving `PartialEq` and can implement `Eq`",
481 "consider deriving `Eq` as well",
482 "PartialEq, Eq".to_string(),
483 Applicability::MachineApplicable,
489 /// Creates the `ParamEnv` used for the give type's derived `Eq` impl.
490 fn param_env_for_derived_eq(tcx: TyCtxt<'_>, did: DefId, eq_trait_id: DefId) -> ParamEnv<'_> {
491 // Initial map from generic index to param def.
492 // Vec<(param_def, needs_eq)>
497 .map(|p| (p, matches!(p.kind, GenericParamDefKind::Type { .. })))
498 .collect::<Vec<_>>();
500 let ty_predicates = tcx.predicates_of(did).predicates;
501 for (p, _) in ty_predicates {
502 if let PredicateKind::Clause(Clause::Trait(p)) = p.kind().skip_binder()
503 && p.trait_ref.def_id == eq_trait_id
504 && let ty::Param(self_ty) = p.trait_ref.self_ty().kind()
505 && p.constness == BoundConstness::NotConst
507 // Flag types which already have an `Eq` bound.
508 params[self_ty.index as usize].1 = false;
513 tcx.mk_predicates(ty_predicates.iter().map(|&(p, _)| p).chain(
514 params.iter().filter(|&&(_, needs_eq)| needs_eq).map(|&(param, _)| {
515 tcx.mk_predicate(Binder::dummy(PredicateKind::Clause(Clause::Trait(TraitPredicate {
516 trait_ref: tcx.mk_trait_ref(eq_trait_id, [tcx.mk_param_from_def(param)]),
517 constness: BoundConstness::NotConst,
518 polarity: ImplPolarity::Positive,