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, 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, GenericArgKind, GenericParamDefKind, ImplPolarity, ParamEnv, PredicateKind,
18 TraitPredicate, Ty, TyCtxt,
20 use rustc_session::{declare_lint_pass, declare_tool_lint};
21 use rustc_span::def_id::LocalDefId;
22 use rustc_span::source_map::Span;
25 declare_clippy_lint! {
27 /// Checks for deriving `Hash` but implementing `PartialEq`
28 /// explicitly or vice versa.
30 /// ### Why is this bad?
31 /// The implementation of these traits must agree (for
32 /// example for use with `HashMap`) so it’s probably a bad idea to use a
33 /// default-generated `Hash` implementation with an explicitly defined
34 /// `PartialEq`. In particular, the following must hold for any type:
37 /// k1 == k2 ⇒ hash(k1) == hash(k2)
45 /// impl PartialEq for Foo {
49 #[clippy::version = "pre 1.29.0"]
50 pub DERIVED_HASH_WITH_MANUAL_EQ,
52 "deriving `Hash` but implementing `PartialEq` explicitly"
55 declare_clippy_lint! {
57 /// Checks for deriving `Ord` but implementing `PartialOrd`
58 /// explicitly or vice versa.
60 /// ### Why is this bad?
61 /// The implementation of these traits must agree (for
62 /// example for use with `sort`) so it’s probably a bad idea to use a
63 /// default-generated `Ord` implementation with an explicitly defined
64 /// `PartialOrd`. In particular, the following must hold for any type
65 /// implementing `Ord`:
68 /// k1.cmp(&k2) == k1.partial_cmp(&k2).unwrap()
73 /// #[derive(Ord, PartialEq, Eq)]
76 /// impl PartialOrd for Foo {
82 /// #[derive(PartialEq, Eq)]
85 /// impl PartialOrd for Foo {
86 /// fn partial_cmp(&self, other: &Foo) -> Option<Ordering> {
87 /// Some(self.cmp(other))
91 /// impl Ord for Foo {
95 /// or, if you don't need a custom ordering:
97 /// #[derive(Ord, PartialOrd, PartialEq, Eq)]
100 #[clippy::version = "1.47.0"]
101 pub DERIVE_ORD_XOR_PARTIAL_ORD,
103 "deriving `Ord` but implementing `PartialOrd` explicitly"
106 declare_clippy_lint! {
108 /// Checks for explicit `Clone` implementations for `Copy`
111 /// ### Why is this bad?
112 /// To avoid surprising behavior, these traits should
113 /// agree and the behavior of `Copy` cannot be overridden. In almost all
114 /// situations a `Copy` type should have a `Clone` implementation that does
115 /// nothing more than copy the object, which is what `#[derive(Copy, Clone)]`
123 /// impl Clone for Foo {
127 #[clippy::version = "pre 1.29.0"]
128 pub EXPL_IMPL_CLONE_ON_COPY,
130 "implementing `Clone` explicitly on `Copy` types"
133 declare_clippy_lint! {
135 /// Checks for deriving `serde::Deserialize` on a type that
136 /// has methods using `unsafe`.
138 /// ### Why is this bad?
139 /// Deriving `serde::Deserialize` will create a constructor
140 /// that may violate invariants hold by another constructor.
144 /// use serde::Deserialize;
146 /// #[derive(Deserialize)]
152 /// pub fn new() -> Self {
156 /// pub unsafe fn parts() -> (&str, &str) {
157 /// // assumes invariants hold
161 #[clippy::version = "1.45.0"]
162 pub UNSAFE_DERIVE_DESERIALIZE,
164 "deriving `serde::Deserialize` on a type that has methods using `unsafe`"
167 declare_clippy_lint! {
169 /// Checks for types that derive `PartialEq` and could implement `Eq`.
171 /// ### Why is this bad?
172 /// If a type `T` derives `PartialEq` and all of its members implement `Eq`,
173 /// then `T` can always implement `Eq`. Implementing `Eq` allows `T` to be used
174 /// in APIs that require `Eq` types. It also allows structs containing `T` to derive
179 /// #[derive(PartialEq)]
182 /// i_am_eq_too: Vec<String>,
187 /// #[derive(PartialEq, Eq)]
190 /// i_am_eq_too: Vec<String>,
193 #[clippy::version = "1.63.0"]
194 pub DERIVE_PARTIAL_EQ_WITHOUT_EQ,
196 "deriving `PartialEq` on a type that can implement `Eq`, without implementing `Eq`"
199 declare_lint_pass!(Derive => [
200 EXPL_IMPL_CLONE_ON_COPY,
201 DERIVED_HASH_WITH_MANUAL_EQ,
202 DERIVE_ORD_XOR_PARTIAL_ORD,
203 UNSAFE_DERIVE_DESERIALIZE,
204 DERIVE_PARTIAL_EQ_WITHOUT_EQ
207 impl<'tcx> LateLintPass<'tcx> for Derive {
208 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
209 if let ItemKind::Impl(Impl {
210 of_trait: Some(ref trait_ref),
214 let ty = cx.tcx.type_of(item.owner_id);
215 let is_automatically_derived = cx.tcx.has_attr(item.owner_id.to_def_id(), sym::automatically_derived);
217 check_hash_peq(cx, item.span, trait_ref, ty, is_automatically_derived);
218 check_ord_partial_ord(cx, item.span, trait_ref, ty, is_automatically_derived);
220 if is_automatically_derived {
221 check_unsafe_derive_deserialize(cx, item, trait_ref, ty);
222 check_partial_eq_without_eq(cx, item.span, trait_ref, ty);
224 check_copy_clone(cx, item, trait_ref, ty);
230 /// Implementation of the `DERIVED_HASH_WITH_MANUAL_EQ` lint.
231 fn check_hash_peq<'tcx>(
232 cx: &LateContext<'tcx>,
234 trait_ref: &hir::TraitRef<'_>,
236 hash_is_automatically_derived: bool,
239 if let Some(peq_trait_def_id) = cx.tcx.lang_items().eq_trait();
240 if let Some(def_id) = trait_ref.trait_def_id();
241 if cx.tcx.is_diagnostic_item(sym::Hash, def_id);
243 // Look for the PartialEq implementations for `ty`
244 cx.tcx.for_each_relevant_impl(peq_trait_def_id, ty, |impl_id| {
245 let peq_is_automatically_derived = cx.tcx.has_attr(impl_id, sym::automatically_derived);
247 if !hash_is_automatically_derived || peq_is_automatically_derived {
251 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
253 // Only care about `impl PartialEq<Foo> for Foo`
254 // For `impl PartialEq<B> for A, input_types is [A, B]
255 if trait_ref.subst_identity().substs.type_at(1) == ty {
258 DERIVED_HASH_WITH_MANUAL_EQ,
260 "you are deriving `Hash` but have implemented `PartialEq` explicitly",
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);
265 cx.tcx.hir().span(hir_id),
266 "`PartialEq` implemented here"
277 /// Implementation of the `DERIVE_ORD_XOR_PARTIAL_ORD` lint.
278 fn check_ord_partial_ord<'tcx>(
279 cx: &LateContext<'tcx>,
281 trait_ref: &hir::TraitRef<'_>,
283 ord_is_automatically_derived: bool,
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;
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);
295 if partial_ord_is_automatically_derived == ord_is_automatically_derived {
299 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
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.subst_identity().substs.type_at(1) == ty {
304 let mess = if partial_ord_is_automatically_derived {
305 "you are implementing `Ord` explicitly but have derived `PartialOrd`"
307 "you are deriving `Ord` but have implemented `PartialOrd` explicitly"
312 DERIVE_ORD_XOR_PARTIAL_ORD,
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);
319 cx.tcx.hir().span(hir_id),
320 "`PartialOrd` implemented here"
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,
337 let Some(copy_id) = cx.tcx.lang_items().copy_trait() else { return };
338 let (ty_adt, ty_subs) = match *ty.kind() {
339 // Unions can't derive clone.
340 ty::Adt(adt, subs) if !adt.is_union() => (adt, subs),
343 // If the current self type doesn't implement Copy (due to generic constraints), search to see if
344 // there's a Copy impl for any instance of the adt.
345 if !is_copy(cx, ty) {
346 if ty_subs.non_erasable_generics().next().is_some() {
347 let has_copy_impl = cx.tcx.all_local_trait_impls(()).get(©_id).map_or(false, |impls| {
350 .any(|&id| matches!(cx.tcx.type_of(id).kind(), ty::Adt(adt, _) if ty_adt.did() == adt.did()))
359 // Derive constrains all generic types to requiring Clone. Check if any type is not constrained for
361 if ty_subs.types().any(|ty| !implements_trait(cx, ty, clone_id, &[])) {
364 // `#[repr(packed)]` structs with type/const parameters can't derive `Clone`.
365 // https://github.com/rust-lang/rust-clippy/issues/10188
366 if ty_adt.repr().packed()
369 .any(|arg| matches!(arg.unpack(), GenericArgKind::Type(_) | GenericArgKind::Const(_)))
376 EXPL_IMPL_CLONE_ON_COPY,
378 "you are implementing `Clone` explicitly on a `Copy` type",
380 "consider deriving `Clone` or removing `Copy`",
384 /// Implementation of the `UNSAFE_DERIVE_DESERIALIZE` lint.
385 fn check_unsafe_derive_deserialize<'tcx>(
386 cx: &LateContext<'tcx>,
388 trait_ref: &hir::TraitRef<'_>,
391 fn has_unsafe<'tcx>(cx: &LateContext<'tcx>, item: &'tcx Item<'_>) -> bool {
392 let mut visitor = UnsafeVisitor { cx, has_unsafe: false };
393 walk_item(&mut visitor, item);
398 if let Some(trait_def_id) = trait_ref.trait_def_id();
399 if match_def_path(cx, trait_def_id, &paths::SERDE_DESERIALIZE);
400 if let ty::Adt(def, _) = ty.kind();
401 if let Some(local_def_id) = def.did().as_local();
402 let adt_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
403 if !is_lint_allowed(cx, UNSAFE_DERIVE_DESERIALIZE, adt_hir_id);
404 if cx.tcx.inherent_impls(def.did())
406 .map(|imp_did| cx.tcx.hir().expect_item(imp_did.expect_local()))
407 .any(|imp| has_unsafe(cx, imp));
411 UNSAFE_DERIVE_DESERIALIZE,
413 "you are deriving `serde::Deserialize` on a type that has methods using `unsafe`",
415 "consider implementing `serde::Deserialize` manually. See https://serde.rs/impl-deserialize.html"
421 struct UnsafeVisitor<'a, 'tcx> {
422 cx: &'a LateContext<'tcx>,
426 impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> {
427 type NestedFilter = nested_filter::All;
429 fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: BodyId, _: Span, id: LocalDefId) {
435 if let Some(header) = kind.header();
436 if header.unsafety == Unsafety::Unsafe;
438 self.has_unsafe = true;
442 walk_fn(self, kind, decl, body_id, id);
445 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
450 if let ExprKind::Block(block, _) = expr.kind {
451 if block.rules == BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) {
452 self.has_unsafe = true;
456 walk_expr(self, expr);
459 fn nested_visit_map(&mut self) -> Self::Map {
464 /// Implementation of the `DERIVE_PARTIAL_EQ_WITHOUT_EQ` lint.
465 fn check_partial_eq_without_eq<'tcx>(cx: &LateContext<'tcx>, span: Span, trait_ref: &hir::TraitRef<'_>, ty: Ty<'tcx>) {
467 if let ty::Adt(adt, substs) = ty.kind();
468 if cx.tcx.visibility(adt.did()).is_public();
469 if let Some(eq_trait_def_id) = cx.tcx.get_diagnostic_item(sym::Eq);
470 if let Some(def_id) = trait_ref.trait_def_id();
471 if cx.tcx.is_diagnostic_item(sym::PartialEq, def_id);
472 let param_env = param_env_for_derived_eq(cx.tcx, adt.did(), eq_trait_def_id);
473 if !implements_trait_with_env(cx.tcx, param_env, ty, eq_trait_def_id, []);
474 // If all of our fields implement `Eq`, we can implement `Eq` too
477 .map(|f| f.ty(cx.tcx, substs))
478 .all(|ty| implements_trait_with_env(cx.tcx, param_env, ty, eq_trait_def_id, []));
482 DERIVE_PARTIAL_EQ_WITHOUT_EQ,
483 span.ctxt().outer_expn_data().call_site,
484 "you are deriving `PartialEq` and can implement `Eq`",
485 "consider deriving `Eq` as well",
486 "PartialEq, Eq".to_string(),
487 Applicability::MachineApplicable,
493 /// Creates the `ParamEnv` used for the give type's derived `Eq` impl.
494 fn param_env_for_derived_eq(tcx: TyCtxt<'_>, did: DefId, eq_trait_id: DefId) -> ParamEnv<'_> {
495 // Initial map from generic index to param def.
496 // Vec<(param_def, needs_eq)>
501 .map(|p| (p, matches!(p.kind, GenericParamDefKind::Type { .. })))
502 .collect::<Vec<_>>();
504 let ty_predicates = tcx.predicates_of(did).predicates;
505 for (p, _) in ty_predicates {
506 if let PredicateKind::Clause(Clause::Trait(p)) = p.kind().skip_binder()
507 && p.trait_ref.def_id == eq_trait_id
508 && let ty::Param(self_ty) = p.trait_ref.self_ty().kind()
509 && p.constness == BoundConstness::NotConst
511 // Flag types which already have an `Eq` bound.
512 params[self_ty.index as usize].1 = false;
517 tcx.mk_predicates(ty_predicates.iter().map(|&(p, _)| p).chain(
518 params.iter().filter(|&&(_, needs_eq)| needs_eq).map(|&(param, _)| {
519 tcx.mk_predicate(Binder::dummy(PredicateKind::Clause(Clause::Trait(TraitPredicate {
520 trait_ref: tcx.mk_trait_ref(eq_trait_id, [tcx.mk_param_from_def(param)]),
521 constness: BoundConstness::NotConst,
522 polarity: ImplPolarity::Positive,