]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/derive.rs
Auto merge of #3597 - xfix:match-ergonomics, r=phansch
[rust.git] / clippy_lints / src / derive.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::utils::paths;
11 use crate::utils::{is_automatically_derived, is_copy, match_path, span_lint_and_then};
12 use if_chain::if_chain;
13 use rustc::hir::*;
14 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
15 use rustc::ty::{self, Ty};
16 use rustc::{declare_tool_lint, lint_array};
17 use syntax::source_map::Span;
18
19 /// **What it does:** Checks for deriving `Hash` but implementing `PartialEq`
20 /// explicitly or vice versa.
21 ///
22 /// **Why is this bad?** The implementation of these traits must agree (for
23 /// example for use with `HashMap`) so it’s probably a bad idea to use a
24 /// default-generated `Hash` implementation with an explicitly defined
25 /// `PartialEq`. In particular, the following must hold for any type:
26 ///
27 /// ```rust
28 /// k1 == k2 ⇒ hash(k1) == hash(k2)
29 /// ```
30 ///
31 /// **Known problems:** None.
32 ///
33 /// **Example:**
34 /// ```rust
35 /// #[derive(Hash)]
36 /// struct Foo;
37 ///
38 /// impl PartialEq for Foo {
39 ///     ...
40 /// }
41 /// ```
42 declare_clippy_lint! {
43     pub DERIVE_HASH_XOR_EQ,
44     correctness,
45     "deriving `Hash` but implementing `PartialEq` explicitly"
46 }
47
48 /// **What it does:** Checks for explicit `Clone` implementations for `Copy`
49 /// types.
50 ///
51 /// **Why is this bad?** To avoid surprising behaviour, these traits should
52 /// agree and the behaviour of `Copy` cannot be overridden. In almost all
53 /// situations a `Copy` type should have a `Clone` implementation that does
54 /// nothing more than copy the object, which is what `#[derive(Copy, Clone)]`
55 /// gets you.
56 ///
57 /// **Known problems:** Bounds of generic types are sometimes wrong: https://github.com/rust-lang/rust/issues/26925
58 ///
59 /// **Example:**
60 /// ```rust
61 /// #[derive(Copy)]
62 /// struct Foo;
63 ///
64 /// impl Clone for Foo {
65 ///     ..
66 /// }
67 /// ```
68 declare_clippy_lint! {
69     pub EXPL_IMPL_CLONE_ON_COPY,
70     pedantic,
71     "implementing `Clone` explicitly on `Copy` types"
72 }
73
74 pub struct Derive;
75
76 impl LintPass for Derive {
77     fn get_lints(&self) -> LintArray {
78         lint_array!(EXPL_IMPL_CLONE_ON_COPY, DERIVE_HASH_XOR_EQ)
79     }
80 }
81
82 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Derive {
83     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
84         if let ItemKind::Impl(_, _, _, _, Some(ref trait_ref), _, _) = item.node {
85             let ty = cx.tcx.type_of(cx.tcx.hir().local_def_id(item.id));
86             let is_automatically_derived = is_automatically_derived(&*item.attrs);
87
88             check_hash_peq(cx, item.span, trait_ref, ty, is_automatically_derived);
89
90             if !is_automatically_derived {
91                 check_copy_clone(cx, item, trait_ref, ty);
92             }
93         }
94     }
95 }
96
97 /// Implementation of the `DERIVE_HASH_XOR_EQ` lint.
98 fn check_hash_peq<'a, 'tcx>(
99     cx: &LateContext<'a, 'tcx>,
100     span: Span,
101     trait_ref: &TraitRef,
102     ty: Ty<'tcx>,
103     hash_is_automatically_derived: bool,
104 ) {
105     if_chain! {
106         if match_path(&trait_ref.path, &paths::HASH);
107         if let Some(peq_trait_def_id) = cx.tcx.lang_items().eq_trait();
108         then {
109             // Look for the PartialEq implementations for `ty`
110             cx.tcx.for_each_relevant_impl(peq_trait_def_id, ty, |impl_id| {
111                 let peq_is_automatically_derived = is_automatically_derived(&cx.tcx.get_attrs(impl_id));
112
113                 if peq_is_automatically_derived == hash_is_automatically_derived {
114                     return;
115                 }
116
117                 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
118
119                 // Only care about `impl PartialEq<Foo> for Foo`
120                 // For `impl PartialEq<B> for A, input_types is [A, B]
121                 if trait_ref.substs.type_at(1) == ty {
122                     let mess = if peq_is_automatically_derived {
123                         "you are implementing `Hash` explicitly but have derived `PartialEq`"
124                     } else {
125                         "you are deriving `Hash` but have implemented `PartialEq` explicitly"
126                     };
127
128                     span_lint_and_then(
129                         cx, DERIVE_HASH_XOR_EQ, span,
130                         mess,
131                         |db| {
132                         if let Some(node_id) = cx.tcx.hir().as_local_node_id(impl_id) {
133                             db.span_note(
134                                 cx.tcx.hir().span(node_id),
135                                 "`PartialEq` implemented here"
136                             );
137                         }
138                     });
139                 }
140             });
141         }
142     }
143 }
144
145 /// Implementation of the `EXPL_IMPL_CLONE_ON_COPY` lint.
146 fn check_copy_clone<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, item: &Item, trait_ref: &TraitRef, ty: Ty<'tcx>) {
147     if match_path(&trait_ref.path, &paths::CLONE_TRAIT) {
148         if !is_copy(cx, ty) {
149             return;
150         }
151
152         match ty.sty {
153             ty::Adt(def, _) if def.is_union() => return,
154
155             // Some types are not Clone by default but could be cloned “by hand” if necessary
156             ty::Adt(def, substs) => {
157                 for variant in &def.variants {
158                     for field in &variant.fields {
159                         if let ty::FnDef(..) = field.ty(cx.tcx, substs).sty {
160                             return;
161                         }
162                     }
163                     for subst in substs {
164                         if let ty::subst::UnpackedKind::Type(subst) = subst.unpack() {
165                             if let ty::Param(_) = subst.sty {
166                                 return;
167                             }
168                         }
169                     }
170                 }
171             },
172             _ => (),
173         }
174
175         span_lint_and_then(
176             cx,
177             EXPL_IMPL_CLONE_ON_COPY,
178             item.span,
179             "you are implementing `Clone` explicitly on a `Copy` type",
180             |db| {
181                 db.span_note(item.span, "consider deriving `Clone` or removing `Copy`");
182             },
183         );
184     }
185 }