]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/derive.rs
non_copy_const: remove incorrect suggestion
[rust.git] / clippy_lints / src / derive.rs
1 use crate::utils::paths;
2 use crate::utils::{is_automatically_derived, is_copy, match_path, span_lint_and_then};
3 use if_chain::if_chain;
4 use rustc::hir::*;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::ty::{self, Ty};
7 use rustc::{declare_lint_pass, declare_tool_lint};
8 use syntax::source_map::Span;
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks for deriving `Hash` but implementing `PartialEq`
12     /// explicitly or vice versa.
13     ///
14     /// **Why is this bad?** The implementation of these traits must agree (for
15     /// example for use with `HashMap`) so it’s probably a bad idea to use a
16     /// default-generated `Hash` implementation with an explicitly defined
17     /// `PartialEq`. In particular, the following must hold for any type:
18     ///
19     /// ```text
20     /// k1 == k2 ⇒ hash(k1) == hash(k2)
21     /// ```
22     ///
23     /// **Known problems:** None.
24     ///
25     /// **Example:**
26     /// ```ignore
27     /// #[derive(Hash)]
28     /// struct Foo;
29     ///
30     /// impl PartialEq for Foo {
31     ///     ...
32     /// }
33     /// ```
34     pub DERIVE_HASH_XOR_EQ,
35     correctness,
36     "deriving `Hash` but implementing `PartialEq` explicitly"
37 }
38
39 declare_clippy_lint! {
40     /// **What it does:** Checks for explicit `Clone` implementations for `Copy`
41     /// types.
42     ///
43     /// **Why is this bad?** To avoid surprising behaviour, these traits should
44     /// agree and the behaviour of `Copy` cannot be overridden. In almost all
45     /// situations a `Copy` type should have a `Clone` implementation that does
46     /// nothing more than copy the object, which is what `#[derive(Copy, Clone)]`
47     /// gets you.
48     ///
49     /// **Known problems:** Bounds of generic types are sometimes wrong: https://github.com/rust-lang/rust/issues/26925
50     ///
51     /// **Example:**
52     /// ```rust,ignore
53     /// #[derive(Copy)]
54     /// struct Foo;
55     ///
56     /// impl Clone for Foo {
57     ///     // ..
58     /// }
59     /// ```
60     pub EXPL_IMPL_CLONE_ON_COPY,
61     pedantic,
62     "implementing `Clone` explicitly on `Copy` types"
63 }
64
65 declare_lint_pass!(Derive => [EXPL_IMPL_CLONE_ON_COPY, DERIVE_HASH_XOR_EQ]);
66
67 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Derive {
68     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
69         if let ItemKind::Impl(_, _, _, _, Some(ref trait_ref), _, _) = item.node {
70             let ty = cx.tcx.type_of(cx.tcx.hir().local_def_id(item.hir_id));
71             let is_automatically_derived = is_automatically_derived(&*item.attrs);
72
73             check_hash_peq(cx, item.span, trait_ref, ty, is_automatically_derived);
74
75             if !is_automatically_derived {
76                 check_copy_clone(cx, item, trait_ref, ty);
77             }
78         }
79     }
80 }
81
82 /// Implementation of the `DERIVE_HASH_XOR_EQ` lint.
83 fn check_hash_peq<'a, 'tcx>(
84     cx: &LateContext<'a, 'tcx>,
85     span: Span,
86     trait_ref: &TraitRef,
87     ty: Ty<'tcx>,
88     hash_is_automatically_derived: bool,
89 ) {
90     if_chain! {
91         if match_path(&trait_ref.path, &paths::HASH);
92         if let Some(peq_trait_def_id) = cx.tcx.lang_items().eq_trait();
93         then {
94             // Look for the PartialEq implementations for `ty`
95             cx.tcx.for_each_relevant_impl(peq_trait_def_id, ty, |impl_id| {
96                 let peq_is_automatically_derived = is_automatically_derived(&cx.tcx.get_attrs(impl_id));
97
98                 if peq_is_automatically_derived == hash_is_automatically_derived {
99                     return;
100                 }
101
102                 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
103
104                 // Only care about `impl PartialEq<Foo> for Foo`
105                 // For `impl PartialEq<B> for A, input_types is [A, B]
106                 if trait_ref.substs.type_at(1) == ty {
107                     let mess = if peq_is_automatically_derived {
108                         "you are implementing `Hash` explicitly but have derived `PartialEq`"
109                     } else {
110                         "you are deriving `Hash` but have implemented `PartialEq` explicitly"
111                     };
112
113                     span_lint_and_then(
114                         cx, DERIVE_HASH_XOR_EQ, span,
115                         mess,
116                         |db| {
117                         if let Some(node_id) = cx.tcx.hir().as_local_hir_id(impl_id) {
118                             db.span_note(
119                                 cx.tcx.hir().span(node_id),
120                                 "`PartialEq` implemented here"
121                             );
122                         }
123                     });
124                 }
125             });
126         }
127     }
128 }
129
130 /// Implementation of the `EXPL_IMPL_CLONE_ON_COPY` lint.
131 fn check_copy_clone<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, item: &Item, trait_ref: &TraitRef, ty: Ty<'tcx>) {
132     if match_path(&trait_ref.path, &paths::CLONE_TRAIT) {
133         if !is_copy(cx, ty) {
134             return;
135         }
136
137         match ty.sty {
138             ty::Adt(def, _) if def.is_union() => return,
139
140             // Some types are not Clone by default but could be cloned “by hand” if necessary
141             ty::Adt(def, substs) => {
142                 for variant in &def.variants {
143                     for field in &variant.fields {
144                         if let ty::FnDef(..) = field.ty(cx.tcx, substs).sty {
145                             return;
146                         }
147                     }
148                     for subst in substs {
149                         if let ty::subst::UnpackedKind::Type(subst) = subst.unpack() {
150                             if let ty::Param(_) = subst.sty {
151                                 return;
152                             }
153                         }
154                     }
155                 }
156             },
157             _ => (),
158         }
159
160         span_lint_and_then(
161             cx,
162             EXPL_IMPL_CLONE_ON_COPY,
163             item.span,
164             "you are implementing `Clone` explicitly on a `Copy` type",
165             |db| {
166                 db.span_note(item.span, "consider deriving `Clone` or removing `Copy`");
167             },
168         );
169     }
170 }