]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/derive.rs
Remove useless `if_let_chain`
[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>, hash_is_automatically_derived: bool) {
88     if_let_chain! {[
89         match_path(&trait_ref.path, &paths::HASH),
90         let Some(peq_trait_def_id) = cx.tcx.lang_items.eq_trait()
91     ], {
92         let peq_trait_def = cx.tcx.lookup_trait_def(peq_trait_def_id);
93
94         // Look for the PartialEq implementations for `ty`
95         peq_trait_def.for_each_relevant_impl(cx.tcx, ty, |impl_id| {
96             let peq_is_automatically_derived = cx.tcx.get_attrs(impl_id).iter().any(is_automatically_derived);
97
98             if peq_is_automatically_derived == hash_is_automatically_derived {
99                 return;
100             }
101
102             let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
103
104             // Only care about `impl PartialEq<Foo> for Foo`
105             if trait_ref.input_types()[0] == ty {
106                 let mess = if peq_is_automatically_derived {
107                     "you are implementing `Hash` explicitly but have derived `PartialEq`"
108                 } else {
109                     "you are deriving `Hash` but have implemented `PartialEq` explicitly"
110                 };
111
112                 span_lint_and_then(
113                     cx, DERIVE_HASH_XOR_EQ, span,
114                     mess,
115                     |db| {
116                     if let Some(node_id) = cx.tcx.map.as_local_node_id(impl_id) {
117                         db.span_note(
118                             cx.tcx.map.span(node_id),
119                             "`PartialEq` implemented here"
120                         );
121                     }
122                 });
123             }
124         });
125     }}
126 }
127
128 /// Implementation of the `EXPL_IMPL_CLONE_ON_COPY` lint.
129 fn check_copy_clone<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, item: &Item, trait_ref: &TraitRef, ty: ty::Ty<'tcx>) {
130     if match_path(&trait_ref.path, &paths::CLONE_TRAIT) {
131         let parameter_environment = ty::ParameterEnvironment::for_item(cx.tcx, item.id);
132         let subst_ty = ty.subst(cx.tcx, parameter_environment.free_substs);
133
134         if subst_ty.moves_by_default(cx.tcx.global_tcx(), &parameter_environment, item.span) {
135             return; // ty is not Copy
136         }
137
138         // Some types are not Clone by default but could be cloned `by hand` if necessary
139         match ty.sty {
140             TypeVariants::TyEnum(def, substs) | TypeVariants::TyStruct(def, substs) => {
141                 for variant in &def.variants {
142                     for field in &variant.fields {
143                         match field.ty(cx.tcx, substs).sty {
144                             TypeVariants::TyArray(_, size) if size > 32 => {
145                                 return;
146                             }
147                             TypeVariants::TyFnPtr(..) => {
148                                 return;
149                             }
150                             TypeVariants::TyTuple(ref tys) if tys.len() > 12 => {
151                                 return;
152                             }
153                             _ => (),
154                         }
155                     }
156                 }
157             }
158             _ => (),
159         }
160
161         span_lint_and_then(cx,
162                            EXPL_IMPL_CLONE_ON_COPY,
163                            item.span,
164                            "you are implementing `Clone` explicitly on a `Copy` type",
165                            |db| {
166                                db.span_note(item.span, "consider deriving `Clone` or removing `Copy`");
167                            });
168     }
169 }
170
171 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d implementations have.
172 fn is_automatically_derived(attr: &Attribute) -> bool {
173     if let MetaItemKind::Word(ref word) = attr.node.value.node {
174         word == &"automatically_derived"
175     } else {
176         false
177     }
178 }