]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/partialeq_ne_impl.rs
Rollup merge of #91562 - dtolnay:asyncspace, r=Mark-Simulacrum
[rust.git] / src / tools / clippy / clippy_lints / src / partialeq_ne_impl.rs
1 use clippy_utils::diagnostics::span_lint_hir;
2 use clippy_utils::is_automatically_derived;
3 use if_chain::if_chain;
4 use rustc_hir::{Impl, Item, ItemKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7 use rustc_span::sym;
8
9 declare_clippy_lint! {
10     /// ### What it does
11     /// Checks for manual re-implementations of `PartialEq::ne`.
12     ///
13     /// ### Why is this bad?
14     /// `PartialEq::ne` is required to always return the
15     /// negated result of `PartialEq::eq`, which is exactly what the default
16     /// implementation does. Therefore, there should never be any need to
17     /// re-implement it.
18     ///
19     /// ### Example
20     /// ```rust
21     /// struct Foo;
22     ///
23     /// impl PartialEq for Foo {
24     ///    fn eq(&self, other: &Foo) -> bool { true }
25     ///    fn ne(&self, other: &Foo) -> bool { !(self == other) }
26     /// }
27     /// ```
28     #[clippy::version = "pre 1.29.0"]
29     pub PARTIALEQ_NE_IMPL,
30     complexity,
31     "re-implementing `PartialEq::ne`"
32 }
33
34 declare_lint_pass!(PartialEqNeImpl => [PARTIALEQ_NE_IMPL]);
35
36 impl<'tcx> LateLintPass<'tcx> for PartialEqNeImpl {
37     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
38         if_chain! {
39             if let ItemKind::Impl(Impl { of_trait: Some(ref trait_ref), items: impl_items, .. }) = item.kind;
40             let attrs = cx.tcx.hir().attrs(item.hir_id());
41             if !is_automatically_derived(attrs);
42             if let Some(eq_trait) = cx.tcx.lang_items().eq_trait();
43             if trait_ref.path.res.def_id() == eq_trait;
44             then {
45                 for impl_item in impl_items {
46                     if impl_item.ident.name == sym::ne {
47                         span_lint_hir(
48                             cx,
49                             PARTIALEQ_NE_IMPL,
50                             impl_item.id.hir_id(),
51                             impl_item.span,
52                             "re-implementing `PartialEq::ne` is unnecessary",
53                         );
54                     }
55                 }
56             }
57         };
58     }
59 }