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