]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/derive.rs
Merge pull request #1000 from Manishearth/doc_whitelist
[rust.git] / clippy_lints / src / derive.rs
1 use rustc::lint::*;
2 use rustc::ty::subst::Subst;
3 use rustc::ty::TypeVariants;
4 use rustc::ty;
5 use rustc::hir::*;
6 use syntax::ast::{Attribute, MetaItemKind};
7 use syntax::codemap::Span;
8 use utils::paths;
9 use utils::{match_path, span_lint_and_then};
10
11 /// **What it does:** This lint warns about deriving `Hash` but implementing `PartialEq`
12 /// explicitly.
13 ///
14 /// **Why is this bad?** The implementation of these traits must agree (for example for use with
15 /// `HashMap`) so it’s probably a bad idea to use a default-generated `Hash` implementation  with
16 /// an explicitly defined `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_lint! {
34     pub DERIVE_HASH_XOR_EQ,
35     Warn,
36     "deriving `Hash` but implementing `PartialEq` explicitly"
37 }
38
39 /// **What it does:** This lint warns about explicit `Clone` implementation for `Copy` types.
40 ///
41 /// **Why is this bad?** To avoid surprising behaviour, these traits should agree and the behaviour
42 /// of `Copy` cannot be overridden. In almost all situations a `Copy` type should have a `Clone`
43 /// implementation that does nothing more than copy the object, which is what
44 /// `#[derive(Copy, Clone)]` gets you.
45 ///
46 /// **Known problems:** None.
47 ///
48 /// **Example:**
49 /// ```rust
50 /// #[derive(Copy)]
51 /// struct Foo;
52 ///
53 /// impl Clone for Foo {
54 ///     ..
55 /// }
56 /// ```
57 declare_lint! {
58     pub EXPL_IMPL_CLONE_ON_COPY,
59     Warn,
60     "implementing `Clone` explicitly on `Copy` types"
61 }
62
63 pub struct Derive;
64
65 impl LintPass for Derive {
66     fn get_lints(&self) -> LintArray {
67         lint_array!(EXPL_IMPL_CLONE_ON_COPY, DERIVE_HASH_XOR_EQ)
68     }
69 }
70
71 impl LateLintPass for Derive {
72     fn check_item(&mut self, cx: &LateContext, item: &Item) {
73         if let ItemImpl(_, _, _, Some(ref trait_ref), _, _) = item.node {
74             let ty = cx.tcx.lookup_item_type(cx.tcx.map.local_def_id(item.id)).ty;
75             let is_automatically_derived = item.attrs.iter().any(is_automatically_derived);
76
77             check_hash_peq(cx, item.span, trait_ref, ty, is_automatically_derived);
78
79             if !is_automatically_derived {
80                 check_copy_clone(cx, item, trait_ref, ty);
81             }
82         }
83     }
84 }
85
86 /// Implementation of the `DERIVE_HASH_XOR_EQ` lint.
87 fn check_hash_peq<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, span: Span, trait_ref: &TraitRef, ty: ty::Ty<'tcx>,
88                                 hash_is_automatically_derived: bool) {
89     if_let_chain! {[
90         match_path(&trait_ref.path, &paths::HASH),
91         let Some(peq_trait_def_id) = cx.tcx.lang_items.eq_trait()
92     ], {
93         let peq_trait_def = cx.tcx.lookup_trait_def(peq_trait_def_id);
94
95         // Look for the PartialEq implementations for `ty`
96         peq_trait_def.for_each_relevant_impl(cx.tcx, ty, |impl_id| {
97             let peq_is_automatically_derived = cx.tcx.get_attrs(impl_id).iter().any(is_automatically_derived);
98
99             if peq_is_automatically_derived == hash_is_automatically_derived {
100                 return;
101             }
102
103             let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
104
105             // Only care about `impl PartialEq<Foo> for Foo`
106             if trait_ref.input_types()[0] == 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.map.as_local_node_id(impl_id) {
118                         db.span_note(
119                             cx.tcx.map.span(node_id),
120                             "`PartialEq` implemented here"
121                         );
122                     }
123                 });
124             }
125         });
126     }}
127 }
128
129 /// Implementation of the `EXPL_IMPL_CLONE_ON_COPY` lint.
130 fn check_copy_clone<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, item: &Item, trait_ref: &TraitRef, ty: ty::Ty<'tcx>) {
131     if match_path(&trait_ref.path, &paths::CLONE_TRAIT) {
132         let parameter_environment = ty::ParameterEnvironment::for_item(cx.tcx, item.id);
133         let subst_ty = ty.subst(cx.tcx, parameter_environment.free_substs);
134
135         if subst_ty.moves_by_default(cx.tcx.global_tcx(), &parameter_environment, item.span) {
136             return; // ty is not Copy
137         }
138
139         // Some types are not Clone by default but could be cloned `by hand` if necessary
140         match ty.sty {
141             TypeVariants::TyEnum(def, substs) |
142             TypeVariants::TyStruct(def, substs) => {
143                 for variant in &def.variants {
144                     for field in &variant.fields {
145                         match field.ty(cx.tcx, substs).sty {
146                             TypeVariants::TyArray(_, size) if size > 32 => {
147                                 return;
148                             }
149                             TypeVariants::TyFnPtr(..) => {
150                                 return;
151                             }
152                             TypeVariants::TyTuple(ref tys) if tys.len() > 12 => {
153                                 return;
154                             }
155                             _ => (),
156                         }
157                     }
158                 }
159             }
160             _ => (),
161         }
162
163         span_lint_and_then(cx,
164                            EXPL_IMPL_CLONE_ON_COPY,
165                            item.span,
166                            "you are implementing `Clone` explicitly on a `Copy` type",
167                            |db| {
168                                db.span_note(item.span, "consider deriving `Clone` or removing `Copy`");
169                            });
170     }
171 }
172
173 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d implementations have.
174 fn is_automatically_derived(attr: &Attribute) -> bool {
175     if let MetaItemKind::Word(ref word) = attr.node.value.node {
176         word == &"automatically_derived"
177     } else {
178         false
179     }
180 }