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, GenericParamDefKind, ImplPolarity, ParamEnv, PredicateKind, TraitPredicate, TraitRef,
18 Ty, TyCtxt, Visibility,
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.def_id);
214 let is_automatically_derived = cx.tcx.has_attr(item.def_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 copy_id = match cx.tcx.lang_items().copy_trait() {
346 let (ty_adt, ty_subs) = match *ty.kind() {
347 // Unions can't derive clone.
348 ty::Adt(adt, subs) if !adt.is_union() => (adt, subs),
351 // If the current self type doesn't implement Copy (due to generic constraints), search to see if
352 // there's a Copy impl for any instance of the adt.
353 if !is_copy(cx, ty) {
354 if ty_subs.non_erasable_generics().next().is_some() {
355 let has_copy_impl = cx.tcx.all_local_trait_impls(()).get(©_id).map_or(false, |impls| {
358 .any(|&id| matches!(cx.tcx.type_of(id).kind(), ty::Adt(adt, _) if ty_adt.did() == adt.did()))
367 // Derive constrains all generic types to requiring Clone. Check if any type is not constrained for
369 if ty_subs.types().any(|ty| !implements_trait(cx, ty, clone_id, &[])) {
375 EXPL_IMPL_CLONE_ON_COPY,
377 "you are implementing `Clone` explicitly on a `Copy` type",
379 "consider deriving `Clone` or removing `Copy`",
383 /// Implementation of the `UNSAFE_DERIVE_DESERIALIZE` lint.
384 fn check_unsafe_derive_deserialize<'tcx>(
385 cx: &LateContext<'tcx>,
387 trait_ref: &hir::TraitRef<'_>,
390 fn has_unsafe<'tcx>(cx: &LateContext<'tcx>, item: &'tcx Item<'_>) -> bool {
391 let mut visitor = UnsafeVisitor { cx, has_unsafe: false };
392 walk_item(&mut visitor, item);
397 if let Some(trait_def_id) = trait_ref.trait_def_id();
398 if match_def_path(cx, trait_def_id, &paths::SERDE_DESERIALIZE);
399 if let ty::Adt(def, _) = ty.kind();
400 if let Some(local_def_id) = def.did().as_local();
401 let adt_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
402 if !is_lint_allowed(cx, UNSAFE_DERIVE_DESERIALIZE, adt_hir_id);
403 if cx.tcx.inherent_impls(def.did())
405 .map(|imp_did| cx.tcx.hir().expect_item(imp_did.expect_local()))
406 .any(|imp| has_unsafe(cx, imp));
410 UNSAFE_DERIVE_DESERIALIZE,
412 "you are deriving `serde::Deserialize` on a type that has methods using `unsafe`",
414 "consider implementing `serde::Deserialize` manually. See https://serde.rs/impl-deserialize.html"
420 struct UnsafeVisitor<'a, 'tcx> {
421 cx: &'a LateContext<'tcx>,
425 impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> {
426 type NestedFilter = nested_filter::All;
428 fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: BodyId, span: Span, id: HirId) {
434 if let Some(header) = kind.header();
435 if header.unsafety == Unsafety::Unsafe;
437 self.has_unsafe = true;
441 walk_fn(self, kind, decl, body_id, span, id);
444 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
449 if let ExprKind::Block(block, _) = expr.kind {
450 if block.rules == BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) {
451 self.has_unsafe = true;
455 walk_expr(self, expr);
458 fn nested_visit_map(&mut self) -> Self::Map {
463 /// Implementation of the `DERIVE_PARTIAL_EQ_WITHOUT_EQ` lint.
464 fn check_partial_eq_without_eq<'tcx>(cx: &LateContext<'tcx>, span: Span, trait_ref: &hir::TraitRef<'_>, ty: Ty<'tcx>) {
466 if let ty::Adt(adt, substs) = ty.kind();
467 if cx.tcx.visibility(adt.did()) == Visibility::Public;
468 if let Some(eq_trait_def_id) = cx.tcx.get_diagnostic_item(sym::Eq);
469 if let Some(def_id) = trait_ref.trait_def_id();
470 if cx.tcx.is_diagnostic_item(sym::PartialEq, def_id);
471 let param_env = param_env_for_derived_eq(cx.tcx, adt.did(), eq_trait_def_id);
472 if !implements_trait_with_env(cx.tcx, param_env, ty, eq_trait_def_id, &[]);
473 // If all of our fields implement `Eq`, we can implement `Eq` too
476 .map(|f| f.ty(cx.tcx, substs))
477 .all(|ty| implements_trait_with_env(cx.tcx, param_env, ty, eq_trait_def_id, &[]));
481 DERIVE_PARTIAL_EQ_WITHOUT_EQ,
482 span.ctxt().outer_expn_data().call_site,
483 "you are deriving `PartialEq` and can implement `Eq`",
484 "consider deriving `Eq` as well",
485 "PartialEq, Eq".to_string(),
486 Applicability::MachineApplicable,
492 /// Creates the `ParamEnv` used for the give type's derived `Eq` impl.
493 fn param_env_for_derived_eq(tcx: TyCtxt<'_>, did: DefId, eq_trait_id: DefId) -> ParamEnv<'_> {
494 // Initial map from generic index to param def.
495 // Vec<(param_def, needs_eq)>
500 .map(|p| (p, matches!(p.kind, GenericParamDefKind::Type { .. })))
501 .collect::<Vec<_>>();
503 let ty_predicates = tcx.predicates_of(did).predicates;
504 for (p, _) in ty_predicates {
505 if let PredicateKind::Trait(p) = p.kind().skip_binder()
506 && p.trait_ref.def_id == eq_trait_id
507 && let ty::Param(self_ty) = p.trait_ref.self_ty().kind()
508 && p.constness == BoundConstness::NotConst
510 // Flag types which already have an `Eq` bound.
511 params[self_ty.index as usize].1 = false;
516 tcx.mk_predicates(ty_predicates.iter().map(|&(p, _)| p).chain(
517 params.iter().filter(|&&(_, needs_eq)| needs_eq).map(|&(param, _)| {
518 tcx.mk_predicate(Binder::dummy(PredicateKind::Trait(TraitPredicate {
519 trait_ref: TraitRef::new(
521 tcx.mk_substs(std::iter::once(tcx.mk_param_from_def(param))),
523 constness: BoundConstness::NotConst,
524 polarity: ImplPolarity::Positive,