]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/derive.rs
modify code
[rust.git] / clippy_lints / src / derive.rs
index 9fad85f8ef432ad8c741730c416b418181a9134a..6d3df260ca25592a59a43e5d75751200c20f7591 100644 (file)
@@ -1,24 +1,25 @@
 use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_note, span_lint_and_then};
 use clippy_utils::paths;
 use clippy_utils::ty::{implements_trait, is_copy};
-use clippy_utils::{get_trait_def_id, is_allowed, is_automatically_derived, match_def_path};
+use clippy_utils::{get_trait_def_id, is_automatically_derived, is_lint_allowed, match_def_path};
 use if_chain::if_chain;
-use rustc_hir::def_id::DefId;
-use rustc_hir::intravisit::{walk_expr, walk_fn, walk_item, FnKind, NestedVisitorMap, Visitor};
+use rustc_hir::intravisit::{walk_expr, walk_fn, walk_item, FnKind, Visitor};
 use rustc_hir::{
     BlockCheckMode, BodyId, Expr, ExprKind, FnDecl, HirId, Impl, Item, ItemKind, TraitRef, UnsafeSource, Unsafety,
 };
 use rustc_lint::{LateContext, LateLintPass};
-use rustc_middle::hir::map::Map;
+use rustc_middle::hir::nested_filter;
 use rustc_middle::ty::{self, Ty};
 use rustc_session::{declare_lint_pass, declare_tool_lint};
-use rustc_span::{def_id::LOCAL_CRATE, source_map::Span};
+use rustc_span::source_map::Span;
 
 declare_clippy_lint! {
-    /// **What it does:** Checks for deriving `Hash` but implementing `PartialEq`
+    /// ### What it does
+    /// Checks for deriving `Hash` but implementing `PartialEq`
     /// explicitly or vice versa.
     ///
-    /// **Why is this bad?** The implementation of these traits must agree (for
+    /// ### Why is this bad?
+    /// The implementation of these traits must agree (for
     /// example for use with `HashMap`) so it’s probably a bad idea to use a
     /// default-generated `Hash` implementation with an explicitly defined
     /// `PartialEq`. In particular, the following must hold for any type:
@@ -27,9 +28,7 @@
     /// k1 == k2 ⇒ hash(k1) == hash(k2)
     /// ```
     ///
-    /// **Known problems:** None.
-    ///
-    /// **Example:**
+    /// ### Example
     /// ```ignore
     /// #[derive(Hash)]
     /// struct Foo;
     ///     ...
     /// }
     /// ```
+    #[clippy::version = "pre 1.29.0"]
     pub DERIVE_HASH_XOR_EQ,
     correctness,
     "deriving `Hash` but implementing `PartialEq` explicitly"
 }
 
 declare_clippy_lint! {
-    /// **What it does:** Checks for deriving `Ord` but implementing `PartialOrd`
+    /// ### What it does
+    /// Checks for deriving `Ord` but implementing `PartialOrd`
     /// explicitly or vice versa.
     ///
-    /// **Why is this bad?** The implementation of these traits must agree (for
+    /// ### Why is this bad?
+    /// The implementation of these traits must agree (for
     /// example for use with `sort`) so it’s probably a bad idea to use a
     /// default-generated `Ord` implementation with an explicitly defined
     /// `PartialOrd`. In particular, the following must hold for any type
     /// k1.cmp(&k2) == k1.partial_cmp(&k2).unwrap()
     /// ```
     ///
-    /// **Known problems:** None.
-    ///
-    /// **Example:**
-    ///
+    /// ### Example
     /// ```rust,ignore
     /// #[derive(Ord, PartialEq, Eq)]
     /// struct Foo;
     /// #[derive(Ord, PartialOrd, PartialEq, Eq)]
     /// struct Foo;
     /// ```
+    #[clippy::version = "1.47.0"]
     pub DERIVE_ORD_XOR_PARTIAL_ORD,
     correctness,
     "deriving `Ord` but implementing `PartialOrd` explicitly"
 }
 
 declare_clippy_lint! {
-    /// **What it does:** Checks for explicit `Clone` implementations for `Copy`
+    /// ### What it does
+    /// Checks for explicit `Clone` implementations for `Copy`
     /// types.
     ///
-    /// **Why is this bad?** To avoid surprising behaviour, these traits should
+    /// ### Why is this bad?
+    /// To avoid surprising behaviour, these traits should
     /// agree and the behaviour of `Copy` cannot be overridden. In almost all
     /// situations a `Copy` type should have a `Clone` implementation that does
     /// nothing more than copy the object, which is what `#[derive(Copy, Clone)]`
     /// gets you.
     ///
-    /// **Known problems:** Bounds of generic types are sometimes wrong: https://github.com/rust-lang/rust/issues/26925
-    ///
-    /// **Example:**
+    /// ### Example
     /// ```rust,ignore
     /// #[derive(Copy)]
     /// struct Foo;
     ///     // ..
     /// }
     /// ```
+    #[clippy::version = "pre 1.29.0"]
     pub EXPL_IMPL_CLONE_ON_COPY,
     pedantic,
     "implementing `Clone` explicitly on `Copy` types"
 }
 
 declare_clippy_lint! {
-    /// **What it does:** Checks for deriving `serde::Deserialize` on a type that
+    /// ### What it does
+    /// Checks for deriving `serde::Deserialize` on a type that
     /// has methods using `unsafe`.
     ///
-    /// **Why is this bad?** Deriving `serde::Deserialize` will create a constructor
+    /// ### Why is this bad?
+    /// Deriving `serde::Deserialize` will create a constructor
     /// that may violate invariants hold by another constructor.
     ///
-    /// **Known problems:** None.
-    ///
-    /// **Example:**
-    ///
+    /// ### Example
     /// ```rust,ignore
     /// use serde::Deserialize;
     ///
     ///     }
     /// }
     /// ```
+    #[clippy::version = "1.45.0"]
     pub UNSAFE_DERIVE_DESERIALIZE,
     pedantic,
     "deriving `serde::Deserialize` on a type that has methods using `unsafe`"
@@ -199,7 +200,7 @@ fn check_hash_peq<'tcx>(
         then {
             // Look for the PartialEq implementations for `ty`
             cx.tcx.for_each_relevant_impl(peq_trait_def_id, ty, |impl_id| {
-                let peq_is_automatically_derived = is_automatically_derived(&cx.tcx.get_attrs(impl_id));
+                let peq_is_automatically_derived = is_automatically_derived(cx.tcx.get_attrs(impl_id));
 
                 if peq_is_automatically_derived == hash_is_automatically_derived {
                     return;
@@ -253,7 +254,7 @@ fn check_ord_partial_ord<'tcx>(
         then {
             // Look for the PartialOrd implementations for `ty`
             cx.tcx.for_each_relevant_impl(partial_ord_trait_def_id, ty, |impl_id| {
-                let partial_ord_is_automatically_derived = is_automatically_derived(&cx.tcx.get_attrs(impl_id));
+                let partial_ord_is_automatically_derived = is_automatically_derived(cx.tcx.get_attrs(impl_id));
 
                 if partial_ord_is_automatically_derived == ord_is_automatically_derived {
                     return;
@@ -310,15 +311,11 @@ fn check_copy_clone<'tcx>(cx: &LateContext<'tcx>, item: &Item<'_>, trait_ref: &T
     // there's a Copy impl for any instance of the adt.
     if !is_copy(cx, ty) {
         if ty_subs.non_erasable_generics().next().is_some() {
-            let has_copy_impl = cx
-                .tcx
-                .all_local_trait_impls(LOCAL_CRATE)
-                .get(&copy_id)
-                .map_or(false, |impls| {
-                    impls
-                        .iter()
-                        .any(|&id| matches!(cx.tcx.type_of(id).kind(), ty::Adt(adt, _) if ty_adt.did == adt.did))
-                });
+            let has_copy_impl = cx.tcx.all_local_trait_impls(()).get(&copy_id).map_or(false, |impls| {
+                impls
+                    .iter()
+                    .any(|&id| matches!(cx.tcx.type_of(id).kind(), ty::Adt(adt, _) if ty_adt.did == adt.did))
+            });
             if !has_copy_impl {
                 return;
             }
@@ -349,11 +346,6 @@ fn check_unsafe_derive_deserialize<'tcx>(
     trait_ref: &TraitRef<'_>,
     ty: Ty<'tcx>,
 ) {
-    fn item_from_def_id<'tcx>(cx: &LateContext<'tcx>, def_id: DefId) -> &'tcx Item<'tcx> {
-        let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
-        cx.tcx.hir().expect_item(hir_id)
-    }
-
     fn has_unsafe<'tcx>(cx: &LateContext<'tcx>, item: &'tcx Item<'_>) -> bool {
         let mut visitor = UnsafeVisitor { cx, has_unsafe: false };
         walk_item(&mut visitor, item);
@@ -366,10 +358,10 @@ fn has_unsafe<'tcx>(cx: &LateContext<'tcx>, item: &'tcx Item<'_>) -> bool {
         if let ty::Adt(def, _) = ty.kind();
         if let Some(local_def_id) = def.did.as_local();
         let adt_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
-        if !is_allowed(cx, UNSAFE_DERIVE_DESERIALIZE, adt_hir_id);
+        if !is_lint_allowed(cx, UNSAFE_DERIVE_DESERIALIZE, adt_hir_id);
         if cx.tcx.inherent_impls(def.did)
             .iter()
-            .map(|imp_did| item_from_def_id(cx, *imp_did))
+            .map(|imp_did| cx.tcx.hir().expect_item(imp_did.expect_local()))
             .any(|imp| has_unsafe(cx, imp));
         then {
             span_lint_and_help(
@@ -390,7 +382,7 @@ struct UnsafeVisitor<'a, 'tcx> {
 }
 
 impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> {
-    type Map = Map<'tcx>;
+    type NestedFilter = nested_filter::All;
 
     fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: BodyId, span: Span, id: HirId) {
         if self.has_unsafe {
@@ -399,7 +391,7 @@ fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: Body
 
         if_chain! {
             if let Some(header) = kind.header();
-            if let Unsafety::Unsafe = header.unsafety;
+            if header.unsafety == Unsafety::Unsafe;
             then {
                 self.has_unsafe = true;
             }
@@ -414,20 +406,15 @@ fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
         }
 
         if let ExprKind::Block(block, _) = expr.kind {
-            match block.rules {
-                BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided)
-                | BlockCheckMode::PushUnsafeBlock(UnsafeSource::UserProvided)
-                | BlockCheckMode::PopUnsafeBlock(UnsafeSource::UserProvided) => {
-                    self.has_unsafe = true;
-                },
-                _ => {},
+            if block.rules == BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) {
+                self.has_unsafe = true;
             }
         }
 
         walk_expr(self, expr);
     }
 
-    fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
-        NestedVisitorMap::All(self.cx.tcx.hir())
+    fn nested_visit_map(&mut self) -> Self::Map {
+        self.cx.tcx.hir()
     }
 }