]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/partialeq_ne_impl.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[rust.git] / clippy_lints / src / partialeq_ne_impl.rs
1 use crate::utils::{is_automatically_derived, span_lint_hir};
2 use if_chain::if_chain;
3 use rustc::hir::*;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::{declare_tool_lint, lint_array};
6
7 declare_clippy_lint! {
8     /// **What it does:** Checks for manual re-implementations of `PartialEq::ne`.
9     ///
10     /// **Why is this bad?** `PartialEq::ne` is required to always return the
11     /// negated result of `PartialEq::eq`, which is exactly what the default
12     /// implementation does. Therefore, there should never be any need to
13     /// re-implement it.
14     ///
15     /// **Known problems:** None.
16     ///
17     /// **Example:**
18     /// ```rust
19     /// struct Foo;
20     ///
21     /// impl PartialEq for Foo {
22     ///    fn eq(&self, other: &Foo) -> bool { ... }
23     ///    fn ne(&self, other: &Foo) -> bool { !(self == other) }
24     /// }
25     /// ```
26     pub PARTIALEQ_NE_IMPL,
27     complexity,
28     "re-implementing `PartialEq::ne`"
29 }
30
31 #[derive(Clone, Copy)]
32 pub struct Pass;
33
34 impl LintPass for Pass {
35     fn get_lints(&self) -> LintArray {
36         lint_array!(PARTIALEQ_NE_IMPL)
37     }
38
39     fn name(&self) -> &'static str {
40         "PartialEqNeImpl"
41     }
42 }
43
44 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
45     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
46         if_chain! {
47             if let ItemKind::Impl(_, _, _, _, Some(ref trait_ref), _, ref impl_items) = item.node;
48             if !is_automatically_derived(&*item.attrs);
49             if let Some(eq_trait) = cx.tcx.lang_items().eq_trait();
50             if trait_ref.path.def.def_id() == eq_trait;
51             then {
52                 for impl_item in impl_items {
53                     if impl_item.ident.name == "ne" {
54                         span_lint_hir(
55                             cx,
56                             PARTIALEQ_NE_IMPL,
57                             impl_item.id.hir_id,
58                             impl_item.span,
59                             "re-implementing `PartialEq::ne` is unnecessary",
60                         );
61                     }
62                 }
63             }
64         };
65     }
66 }