]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/derive.rs
Rustup to rustc 1.13.0-nightly (a23064af5 2016-08-27)
[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:** Checks for deriving `Hash` but implementing `PartialEq`
12 /// explicitly.
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 /// ```rust
20 /// k1 == k2 ⇒ hash(k1) == hash(k2)
21 /// ```
22 ///
23 /// **Known problems:** None.
24 ///
25 /// **Example:**
26 /// ```rust
27 /// #[derive(Hash)]
28 /// struct Foo;
29 ///
30 /// impl PartialEq for Foo {
31 ///     ...
32 /// }
33 /// ```
34 declare_lint! {
35     pub DERIVE_HASH_XOR_EQ,
36     Warn,
37     "deriving `Hash` but implementing `PartialEq` explicitly"
38 }
39
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:** None.
50 ///
51 /// **Example:**
52 /// ```rust
53 /// #[derive(Copy)]
54 /// struct Foo;
55 ///
56 /// impl Clone for Foo {
57 ///     ..
58 /// }
59 /// ```
60 declare_lint! {
61     pub EXPL_IMPL_CLONE_ON_COPY,
62     Warn,
63     "implementing `Clone` explicitly on `Copy` types"
64 }
65
66 pub struct Derive;
67
68 impl LintPass for Derive {
69     fn get_lints(&self) -> LintArray {
70         lint_array!(EXPL_IMPL_CLONE_ON_COPY, DERIVE_HASH_XOR_EQ)
71     }
72 }
73
74 impl LateLintPass for Derive {
75     fn check_item(&mut self, cx: &LateContext, item: &Item) {
76         if let ItemImpl(_, _, _, Some(ref trait_ref), _, _) = item.node {
77             let ty = cx.tcx.lookup_item_type(cx.tcx.map.local_def_id(item.id)).ty;
78             let is_automatically_derived = item.attrs.iter().any(is_automatically_derived);
79
80             check_hash_peq(cx, item.span, trait_ref, ty, is_automatically_derived);
81
82             if !is_automatically_derived {
83                 check_copy_clone(cx, item, trait_ref, ty);
84             }
85         }
86     }
87 }
88
89 /// Implementation of the `DERIVE_HASH_XOR_EQ` lint.
90 fn check_hash_peq<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, span: Span, trait_ref: &TraitRef, ty: ty::Ty<'tcx>,
91                                 hash_is_automatically_derived: bool) {
92     if_let_chain! {[
93         match_path(&trait_ref.path, &paths::HASH),
94         let Some(peq_trait_def_id) = cx.tcx.lang_items.eq_trait()
95     ], {
96         let peq_trait_def = cx.tcx.lookup_trait_def(peq_trait_def_id);
97
98         // Look for the PartialEq implementations for `ty`
99         peq_trait_def.for_each_relevant_impl(cx.tcx, ty, |impl_id| {
100             let peq_is_automatically_derived = cx.tcx.get_attrs(impl_id).iter().any(is_automatically_derived);
101
102             if peq_is_automatically_derived == hash_is_automatically_derived {
103                 return;
104             }
105
106             let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
107
108             // Only care about `impl PartialEq<Foo> for Foo`
109             // For `impl PartialEq<B> for A, input_types is [A, B]
110             if trait_ref.substs.type_at(1) == ty {
111                 let mess = if peq_is_automatically_derived {
112                     "you are implementing `Hash` explicitly but have derived `PartialEq`"
113                 } else {
114                     "you are deriving `Hash` but have implemented `PartialEq` explicitly"
115                 };
116
117                 span_lint_and_then(
118                     cx, DERIVE_HASH_XOR_EQ, span,
119                     mess,
120                     |db| {
121                     if let Some(node_id) = cx.tcx.map.as_local_node_id(impl_id) {
122                         db.span_note(
123                             cx.tcx.map.span(node_id),
124                             "`PartialEq` implemented here"
125                         );
126                     }
127                 });
128             }
129         });
130     }}
131 }
132
133 /// Implementation of the `EXPL_IMPL_CLONE_ON_COPY` lint.
134 fn check_copy_clone<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, item: &Item, trait_ref: &TraitRef, ty: ty::Ty<'tcx>) {
135     if match_path(&trait_ref.path, &paths::CLONE_TRAIT) {
136         let parameter_environment = ty::ParameterEnvironment::for_item(cx.tcx, item.id);
137         let subst_ty = ty.subst(cx.tcx, parameter_environment.free_substs);
138
139         if subst_ty.moves_by_default(cx.tcx.global_tcx(), &parameter_environment, item.span) {
140             return; // ty is not Copy
141         }
142
143         // Some types are not Clone by default but could be cloned `by hand` if necessary
144         match ty.sty {
145             TypeVariants::TyEnum(def, substs) |
146             TypeVariants::TyStruct(def, substs) => {
147                 for variant in &def.variants {
148                     for field in &variant.fields {
149                         match field.ty(cx.tcx, substs).sty {
150                             TypeVariants::TyArray(_, size) if size > 32 => {
151                                 return;
152                             }
153                             TypeVariants::TyFnPtr(..) => {
154                                 return;
155                             }
156                             TypeVariants::TyTuple(tys) if tys.len() > 12 => {
157                                 return;
158                             }
159                             _ => (),
160                         }
161                     }
162                 }
163             }
164             _ => (),
165         }
166
167         span_lint_and_then(cx,
168                            EXPL_IMPL_CLONE_ON_COPY,
169                            item.span,
170                            "you are implementing `Clone` explicitly on a `Copy` type",
171                            |db| {
172                                db.span_note(item.span, "consider deriving `Clone` or removing `Copy`");
173                            });
174     }
175 }
176
177 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d implementations have.
178 fn is_automatically_derived(attr: &Attribute) -> bool {
179     if let MetaItemKind::Word(ref word) = attr.node.value.node {
180         word == &"automatically_derived"
181     } else {
182         false
183     }
184 }