]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/derive.rs
remove nondeterminism by adjusting thresholds
[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::codemap::Span;
7 use utils::paths;
8 use utils::{is_automatically_derived, span_lint_and_then, match_path_old};
9
10 /// **What it does:** Checks for deriving `Hash` but implementing `PartialEq`
11 /// explicitly.
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_lint! {
34     pub DERIVE_HASH_XOR_EQ,
35     Warn,
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:** None.
49 ///
50 /// **Example:**
51 /// ```rust
52 /// #[derive(Copy)]
53 /// struct Foo;
54 ///
55 /// impl Clone for Foo {
56 ///     ..
57 /// }
58 /// ```
59 declare_lint! {
60     pub EXPL_IMPL_CLONE_ON_COPY,
61     Warn,
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
73 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Derive {
74     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
75         if let ItemImpl(_, _, _, Some(ref trait_ref), _, _) = item.node {
76             let ty = cx.tcx.item_type(cx.tcx.map.local_def_id(item.id));
77             let is_automatically_derived = is_automatically_derived(&*item.attrs);
78
79             check_hash_peq(cx, item.span, trait_ref, ty, is_automatically_derived);
80
81             if !is_automatically_derived {
82                 check_copy_clone(cx, item, trait_ref, ty);
83             }
84         }
85     }
86 }
87
88 /// Implementation of the `DERIVE_HASH_XOR_EQ` lint.
89 fn check_hash_peq<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, span: Span, trait_ref: &TraitRef, ty: ty::Ty<'tcx>,
90                             hash_is_automatically_derived: bool) {
91     if_let_chain! {[
92         match_path_old(&trait_ref.path, &paths::HASH),
93         let Some(peq_trait_def_id) = cx.tcx.lang_items.eq_trait()
94     ], {
95         let peq_trait_def = cx.tcx.lookup_trait_def(peq_trait_def_id);
96
97         // Look for the PartialEq implementations for `ty`
98         peq_trait_def.for_each_relevant_impl(cx.tcx, ty, |impl_id| {
99             let peq_is_automatically_derived = is_automatically_derived(&cx.tcx.get_attrs(impl_id));
100
101             if peq_is_automatically_derived == hash_is_automatically_derived {
102                 return;
103             }
104
105             let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
106
107             // Only care about `impl PartialEq<Foo> for Foo`
108             // For `impl PartialEq<B> for A, input_types is [A, B]
109             if trait_ref.substs.type_at(1) == ty {
110                 let mess = if peq_is_automatically_derived {
111                     "you are implementing `Hash` explicitly but have derived `PartialEq`"
112                 } else {
113                     "you are deriving `Hash` but have implemented `PartialEq` explicitly"
114                 };
115
116                 span_lint_and_then(
117                     cx, DERIVE_HASH_XOR_EQ, span,
118                     mess,
119                     |db| {
120                     if let Some(node_id) = cx.tcx.map.as_local_node_id(impl_id) {
121                         db.span_note(
122                             cx.tcx.map.span(node_id),
123                             "`PartialEq` implemented here"
124                         );
125                     }
126                 });
127             }
128         });
129     }}
130 }
131
132 /// Implementation of the `EXPL_IMPL_CLONE_ON_COPY` lint.
133 fn check_copy_clone<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, item: &Item, trait_ref: &TraitRef, ty: ty::Ty<'tcx>) {
134     if match_path_old(&trait_ref.path, &paths::CLONE_TRAIT) {
135         let parameter_environment = ty::ParameterEnvironment::for_item(cx.tcx, item.id);
136         let subst_ty = ty.subst(cx.tcx, parameter_environment.free_substs);
137
138         if subst_ty.moves_by_default(cx.tcx.global_tcx(), &parameter_environment, item.span) {
139             return; // ty is not Copy
140         }
141
142         match ty.sty {
143             TypeVariants::TyAdt(def, _) if def.is_union() => return,
144
145             // Some types are not Clone by default but could be cloned “by hand” if necessary
146             TypeVariants::TyAdt(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 }