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