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