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_automatically_derived, 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};
9 BlockCheckMode, BodyId, Expr, ExprKind, FnDecl, HirId, Impl, Item, ItemKind, TraitRef, UnsafeSource, Unsafety,
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;
18 declare_clippy_lint! {
20 /// Checks for deriving `Hash` but implementing `PartialEq`
21 /// explicitly or vice versa.
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:
30 /// k1 == k2 ⇒ hash(k1) == hash(k2)
38 /// impl PartialEq for Foo {
42 #[clippy::version = "pre 1.29.0"]
43 pub DERIVE_HASH_XOR_EQ,
45 "deriving `Hash` but implementing `PartialEq` explicitly"
48 declare_clippy_lint! {
50 /// Checks for deriving `Ord` but implementing `PartialOrd`
51 /// explicitly or vice versa.
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`:
61 /// k1.cmp(&k2) == k1.partial_cmp(&k2).unwrap()
66 /// #[derive(Ord, PartialEq, Eq)]
69 /// impl PartialOrd for Foo {
75 /// #[derive(PartialEq, Eq)]
78 /// impl PartialOrd for Foo {
79 /// fn partial_cmp(&self, other: &Foo) -> Option<Ordering> {
80 /// Some(self.cmp(other))
84 /// impl Ord for Foo {
88 /// or, if you don't need a custom ordering:
90 /// #[derive(Ord, PartialOrd, PartialEq, Eq)]
93 #[clippy::version = "1.47.0"]
94 pub DERIVE_ORD_XOR_PARTIAL_ORD,
96 "deriving `Ord` but implementing `PartialOrd` explicitly"
99 declare_clippy_lint! {
101 /// Checks for explicit `Clone` implementations for `Copy`
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)]`
116 /// impl Clone for Foo {
120 #[clippy::version = "pre 1.29.0"]
121 pub EXPL_IMPL_CLONE_ON_COPY,
123 "implementing `Clone` explicitly on `Copy` types"
126 declare_clippy_lint! {
128 /// Checks for deriving `serde::Deserialize` on a type that
129 /// has methods using `unsafe`.
131 /// ### Why is this bad?
132 /// Deriving `serde::Deserialize` will create a constructor
133 /// that may violate invariants hold by another constructor.
137 /// use serde::Deserialize;
139 /// #[derive(Deserialize)]
145 /// pub fn new() -> Self {
149 /// pub unsafe fn parts() -> (&str, &str) {
150 /// // assumes invariants hold
154 #[clippy::version = "1.45.0"]
155 pub UNSAFE_DERIVE_DESERIALIZE,
157 "deriving `serde::Deserialize` on a type that has methods using `unsafe`"
160 declare_clippy_lint! {
162 /// Checks for types that derive `PartialEq` and could implement `Eq`.
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
172 /// #[derive(PartialEq)]
175 /// i_am_eq_too: Vec<String>,
180 /// #[derive(PartialEq, Eq)]
183 /// i_am_eq_too: Vec<String>,
186 #[clippy::version = "1.62.0"]
187 pub DERIVE_PARTIAL_EQ_WITHOUT_EQ,
189 "deriving `PartialEq` on a type that can implement `Eq`, without implementing `Eq`"
192 declare_lint_pass!(Derive => [
193 EXPL_IMPL_CLONE_ON_COPY,
195 DERIVE_ORD_XOR_PARTIAL_ORD,
196 UNSAFE_DERIVE_DESERIALIZE,
197 DERIVE_PARTIAL_EQ_WITHOUT_EQ
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),
207 let ty = cx.tcx.type_of(item.def_id);
208 let attrs = cx.tcx.hir().attrs(item.hir_id());
209 let is_automatically_derived = is_automatically_derived(attrs);
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);
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);
218 check_copy_clone(cx, item, trait_ref, ty);
224 /// Implementation of the `DERIVE_HASH_XOR_EQ` lint.
225 fn check_hash_peq<'tcx>(
226 cx: &LateContext<'tcx>,
228 trait_ref: &TraitRef<'_>,
230 hash_is_automatically_derived: bool,
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);
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 = is_automatically_derived(cx.tcx.get_attrs(impl_id));
241 if peq_is_automatically_derived == hash_is_automatically_derived {
245 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
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`"
253 "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: &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 = is_automatically_derived(cx.tcx.get_attrs(impl_id));
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.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: &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 copy_id = match cx.tcx.lang_items().copy_trait() {
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),
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(©_id).map_or(false, |impls| {
353 .any(|&id| matches!(cx.tcx.type_of(id).kind(), ty::Adt(adt, _) if ty_adt.did() == adt.did()))
362 // Derive constrains all generic types to requiring Clone. Check if any type is not constrained for
364 if ty_subs.types().any(|ty| !implements_trait(cx, ty, clone_id, &[])) {
370 EXPL_IMPL_CLONE_ON_COPY,
372 "you are implementing `Clone` explicitly on a `Copy` type",
374 "consider deriving `Clone` or removing `Copy`",
378 /// Implementation of the `UNSAFE_DERIVE_DESERIALIZE` lint.
379 fn check_unsafe_derive_deserialize<'tcx>(
380 cx: &LateContext<'tcx>,
382 trait_ref: &TraitRef<'_>,
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);
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())
400 .map(|imp_did| cx.tcx.hir().expect_item(imp_did.expect_local()))
401 .any(|imp| has_unsafe(cx, imp));
405 UNSAFE_DERIVE_DESERIALIZE,
407 "you are deriving `serde::Deserialize` on a type that has methods using `unsafe`",
409 "consider implementing `serde::Deserialize` manually. See https://serde.rs/impl-deserialize.html"
415 struct UnsafeVisitor<'a, 'tcx> {
416 cx: &'a LateContext<'tcx>,
420 impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> {
421 type NestedFilter = nested_filter::All;
423 fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: BodyId, span: Span, id: HirId) {
429 if let Some(header) = kind.header();
430 if header.unsafety == Unsafety::Unsafe;
432 self.has_unsafe = true;
436 walk_fn(self, kind, decl, body_id, span, id);
439 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
444 if let ExprKind::Block(block, _) = expr.kind {
445 if block.rules == BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) {
446 self.has_unsafe = true;
450 walk_expr(self, expr);
453 fn nested_visit_map(&mut self) -> Self::Map {
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: &TraitRef<'_>, ty: Ty<'tcx>) {
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(def_id) = trait_ref.trait_def_id();
464 if cx.tcx.is_diagnostic_item(sym::PartialEq, def_id);
465 if !implements_trait(cx, ty, eq_trait_def_id, substs);
467 // If all of our fields implement `Eq`, we can implement `Eq` too
468 for variant in adt.variants() {
469 for field in &variant.fields {
470 let ty = field.ty(cx.tcx, substs);
472 if !implements_trait(cx, ty, eq_trait_def_id, substs) {
480 DERIVE_PARTIAL_EQ_WITHOUT_EQ,
481 span.ctxt().outer_expn_data().call_site,
482 "you are deriving `PartialEq` and can implement `Eq`",
483 "consider deriving `Eq` as well",
484 "PartialEq, Eq".to_string(),
485 Applicability::MachineApplicable,