]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/partialeq_ne_impl.rs
Changes lint sugg to bitwise and operator `&`
[rust.git] / clippy_lints / src / partialeq_ne_impl.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::rustc::hir::*;
11 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use crate::utils::{is_automatically_derived, span_lint_node};
14 use if_chain::if_chain;
15
16 /// **What it does:** Checks for manual re-implementations of `PartialEq::ne`.
17 ///
18 /// **Why is this bad?** `PartialEq::ne` is required to always return the
19 /// negated result of `PartialEq::eq`, which is exactly what the default
20 /// implementation does. Therefore, there should never be any need to
21 /// re-implement it.
22 ///
23 /// **Known problems:** None.
24 ///
25 /// **Example:**
26 /// ```rust
27 /// struct Foo;
28 ///
29 /// impl PartialEq for Foo {
30 ///    fn eq(&self, other: &Foo) -> bool { ... }
31 ///    fn ne(&self, other: &Foo) -> bool { !(self == other) }
32 /// }
33 /// ```
34 declare_clippy_lint! {
35     pub PARTIALEQ_NE_IMPL,
36     complexity,
37     "re-implementing `PartialEq::ne`"
38 }
39
40 #[derive(Clone, Copy)]
41 pub struct Pass;
42
43 impl LintPass for Pass {
44     fn get_lints(&self) -> LintArray {
45         lint_array!(PARTIALEQ_NE_IMPL)
46     }
47 }
48
49 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
50     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
51         if_chain! {
52             if let ItemKind::Impl(_, _, _, _, Some(ref trait_ref), _, ref impl_items) = item.node;
53             if !is_automatically_derived(&*item.attrs);
54             if let Some(eq_trait) = cx.tcx.lang_items().eq_trait();
55             if trait_ref.path.def.def_id() == eq_trait;
56             then {
57                 for impl_item in impl_items {
58                     if impl_item.ident.name == "ne" {
59                         span_lint_node(
60                             cx,
61                             PARTIALEQ_NE_IMPL,
62                             impl_item.id.node_id,
63                             impl_item.span,
64                             "re-implementing `PartialEq::ne` is unnecessary",
65                         );
66                     }
67                 }
68             }
69         };
70     }
71 }