]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/derive.rs
Auto merge of #6408 - pro-grammer1:master, r=oli-obk
[rust.git] / clippy_lints / src / derive.rs
1 use crate::utils::paths;
2 use crate::utils::{
3     get_trait_def_id, is_allowed, is_automatically_derived, is_copy, match_def_path, match_path, span_lint_and_help,
4     span_lint_and_note, span_lint_and_then,
5 };
6 use if_chain::if_chain;
7 use rustc_hir::def_id::DefId;
8 use rustc_hir::intravisit::{walk_expr, walk_fn, walk_item, FnKind, NestedVisitorMap, Visitor};
9 use rustc_hir::{
10     BlockCheckMode, BodyId, Expr, ExprKind, FnDecl, HirId, Impl, Item, ItemKind, TraitRef, UnsafeSource, Unsafety,
11 };
12 use rustc_lint::{LateContext, LateLintPass};
13 use rustc_middle::hir::map::Map;
14 use rustc_middle::ty::{self, Ty};
15 use rustc_session::{declare_lint_pass, declare_tool_lint};
16 use rustc_span::source_map::Span;
17
18 declare_clippy_lint! {
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     /// ```text
28     /// k1 == k2 ⇒ hash(k1) == hash(k2)
29     /// ```
30     ///
31     /// **Known problems:** None.
32     ///
33     /// **Example:**
34     /// ```ignore
35     /// #[derive(Hash)]
36     /// struct Foo;
37     ///
38     /// impl PartialEq for Foo {
39     ///     ...
40     /// }
41     /// ```
42     pub DERIVE_HASH_XOR_EQ,
43     correctness,
44     "deriving `Hash` but implementing `PartialEq` explicitly"
45 }
46
47 declare_clippy_lint! {
48     /// **What it does:** Checks for deriving `Ord` but implementing `PartialOrd`
49     /// explicitly or vice versa.
50     ///
51     /// **Why is this bad?** The implementation of these traits must agree (for
52     /// example for use with `sort`) so it’s probably a bad idea to use a
53     /// default-generated `Ord` implementation with an explicitly defined
54     /// `PartialOrd`. In particular, the following must hold for any type
55     /// implementing `Ord`:
56     ///
57     /// ```text
58     /// k1.cmp(&k2) == k1.partial_cmp(&k2).unwrap()
59     /// ```
60     ///
61     /// **Known problems:** None.
62     ///
63     /// **Example:**
64     ///
65     /// ```rust,ignore
66     /// #[derive(Ord, PartialEq, Eq)]
67     /// struct Foo;
68     ///
69     /// impl PartialOrd for Foo {
70     ///     ...
71     /// }
72     /// ```
73     /// Use instead:
74     /// ```rust,ignore
75     /// #[derive(PartialEq, Eq)]
76     /// struct Foo;
77     ///
78     /// impl PartialOrd for Foo {
79     ///     fn partial_cmp(&self, other: &Foo) -> Option<Ordering> {
80     ///        Some(self.cmp(other))
81     ///     }
82     /// }
83     ///
84     /// impl Ord for Foo {
85     ///     ...
86     /// }
87     /// ```
88     /// or, if you don't need a custom ordering:
89     /// ```rust,ignore
90     /// #[derive(Ord, PartialOrd, PartialEq, Eq)]
91     /// struct Foo;
92     /// ```
93     pub DERIVE_ORD_XOR_PARTIAL_ORD,
94     correctness,
95     "deriving `Ord` but implementing `PartialOrd` explicitly"
96 }
97
98 declare_clippy_lint! {
99     /// **What it does:** Checks for explicit `Clone` implementations for `Copy`
100     /// types.
101     ///
102     /// **Why is this bad?** To avoid surprising behaviour, these traits should
103     /// agree and the behaviour of `Copy` cannot be overridden. In almost all
104     /// situations a `Copy` type should have a `Clone` implementation that does
105     /// nothing more than copy the object, which is what `#[derive(Copy, Clone)]`
106     /// gets you.
107     ///
108     /// **Known problems:** Bounds of generic types are sometimes wrong: https://github.com/rust-lang/rust/issues/26925
109     ///
110     /// **Example:**
111     /// ```rust,ignore
112     /// #[derive(Copy)]
113     /// struct Foo;
114     ///
115     /// impl Clone for Foo {
116     ///     // ..
117     /// }
118     /// ```
119     pub EXPL_IMPL_CLONE_ON_COPY,
120     pedantic,
121     "implementing `Clone` explicitly on `Copy` types"
122 }
123
124 declare_clippy_lint! {
125     /// **What it does:** Checks for deriving `serde::Deserialize` on a type that
126     /// has methods using `unsafe`.
127     ///
128     /// **Why is this bad?** Deriving `serde::Deserialize` will create a constructor
129     /// that may violate invariants hold by another constructor.
130     ///
131     /// **Known problems:** None.
132     ///
133     /// **Example:**
134     ///
135     /// ```rust,ignore
136     /// use serde::Deserialize;
137     ///
138     /// #[derive(Deserialize)]
139     /// pub struct Foo {
140     ///     // ..
141     /// }
142     ///
143     /// impl Foo {
144     ///     pub fn new() -> Self {
145     ///         // setup here ..
146     ///     }
147     ///
148     ///     pub unsafe fn parts() -> (&str, &str) {
149     ///         // assumes invariants hold
150     ///     }
151     /// }
152     /// ```
153     pub UNSAFE_DERIVE_DESERIALIZE,
154     pedantic,
155     "deriving `serde::Deserialize` on a type that has methods using `unsafe`"
156 }
157
158 declare_lint_pass!(Derive => [
159     EXPL_IMPL_CLONE_ON_COPY,
160     DERIVE_HASH_XOR_EQ,
161     DERIVE_ORD_XOR_PARTIAL_ORD,
162     UNSAFE_DERIVE_DESERIALIZE
163 ]);
164
165 impl<'tcx> LateLintPass<'tcx> for Derive {
166     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
167         if let ItemKind::Impl(Impl {
168             of_trait: Some(ref trait_ref),
169             ..
170         }) = item.kind
171         {
172             let ty = cx.tcx.type_of(cx.tcx.hir().local_def_id(item.hir_id));
173             let is_automatically_derived = is_automatically_derived(&*item.attrs);
174
175             check_hash_peq(cx, item.span, trait_ref, ty, is_automatically_derived);
176             check_ord_partial_ord(cx, item.span, trait_ref, ty, is_automatically_derived);
177
178             if is_automatically_derived {
179                 check_unsafe_derive_deserialize(cx, item, trait_ref, ty);
180             } else {
181                 check_copy_clone(cx, item, trait_ref, ty);
182             }
183         }
184     }
185 }
186
187 /// Implementation of the `DERIVE_HASH_XOR_EQ` lint.
188 fn check_hash_peq<'tcx>(
189     cx: &LateContext<'tcx>,
190     span: Span,
191     trait_ref: &TraitRef<'_>,
192     ty: Ty<'tcx>,
193     hash_is_automatically_derived: bool,
194 ) {
195     if_chain! {
196         if let Some(peq_trait_def_id) = cx.tcx.lang_items().eq_trait();
197         if let Some(def_id) = trait_ref.trait_def_id();
198         if match_def_path(cx, def_id, &paths::HASH);
199         then {
200             // Look for the PartialEq implementations for `ty`
201             cx.tcx.for_each_relevant_impl(peq_trait_def_id, ty, |impl_id| {
202                 let peq_is_automatically_derived = is_automatically_derived(&cx.tcx.get_attrs(impl_id));
203
204                 if peq_is_automatically_derived == hash_is_automatically_derived {
205                     return;
206                 }
207
208                 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
209
210                 // Only care about `impl PartialEq<Foo> for Foo`
211                 // For `impl PartialEq<B> for A, input_types is [A, B]
212                 if trait_ref.substs.type_at(1) == ty {
213                     let mess = if peq_is_automatically_derived {
214                         "you are implementing `Hash` explicitly but have derived `PartialEq`"
215                     } else {
216                         "you are deriving `Hash` but have implemented `PartialEq` explicitly"
217                     };
218
219                     span_lint_and_then(
220                         cx,
221                         DERIVE_HASH_XOR_EQ,
222                         span,
223                         mess,
224                         |diag| {
225                             if let Some(local_def_id) = impl_id.as_local() {
226                                 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
227                                 diag.span_note(
228                                     cx.tcx.hir().span(hir_id),
229                                     "`PartialEq` implemented here"
230                                 );
231                             }
232                         }
233                     );
234                 }
235             });
236         }
237     }
238 }
239
240 /// Implementation of the `DERIVE_ORD_XOR_PARTIAL_ORD` lint.
241 fn check_ord_partial_ord<'tcx>(
242     cx: &LateContext<'tcx>,
243     span: Span,
244     trait_ref: &TraitRef<'_>,
245     ty: Ty<'tcx>,
246     ord_is_automatically_derived: bool,
247 ) {
248     if_chain! {
249         if let Some(ord_trait_def_id) = get_trait_def_id(cx, &paths::ORD);
250         if let Some(partial_ord_trait_def_id) = cx.tcx.lang_items().partial_ord_trait();
251         if let Some(def_id) = &trait_ref.trait_def_id();
252         if *def_id == ord_trait_def_id;
253         then {
254             // Look for the PartialOrd implementations for `ty`
255             cx.tcx.for_each_relevant_impl(partial_ord_trait_def_id, ty, |impl_id| {
256                 let partial_ord_is_automatically_derived = is_automatically_derived(&cx.tcx.get_attrs(impl_id));
257
258                 if partial_ord_is_automatically_derived == ord_is_automatically_derived {
259                     return;
260                 }
261
262                 let trait_ref = cx.tcx.impl_trait_ref(impl_id).expect("must be a trait implementation");
263
264                 // Only care about `impl PartialOrd<Foo> for Foo`
265                 // For `impl PartialOrd<B> for A, input_types is [A, B]
266                 if trait_ref.substs.type_at(1) == ty {
267                     let mess = if partial_ord_is_automatically_derived {
268                         "you are implementing `Ord` explicitly but have derived `PartialOrd`"
269                     } else {
270                         "you are deriving `Ord` but have implemented `PartialOrd` explicitly"
271                     };
272
273                     span_lint_and_then(
274                         cx,
275                         DERIVE_ORD_XOR_PARTIAL_ORD,
276                         span,
277                         mess,
278                         |diag| {
279                             if let Some(local_def_id) = impl_id.as_local() {
280                                 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
281                                 diag.span_note(
282                                     cx.tcx.hir().span(hir_id),
283                                     "`PartialOrd` implemented here"
284                                 );
285                             }
286                         }
287                     );
288                 }
289             });
290         }
291     }
292 }
293
294 /// Implementation of the `EXPL_IMPL_CLONE_ON_COPY` lint.
295 fn check_copy_clone<'tcx>(cx: &LateContext<'tcx>, item: &Item<'_>, trait_ref: &TraitRef<'_>, ty: Ty<'tcx>) {
296     if match_path(&trait_ref.path, &paths::CLONE_TRAIT) {
297         if !is_copy(cx, ty) {
298             return;
299         }
300
301         match *ty.kind() {
302             ty::Adt(def, _) if def.is_union() => return,
303
304             // Some types are not Clone by default but could be cloned “by hand” if necessary
305             ty::Adt(def, substs) => {
306                 for variant in &def.variants {
307                     for field in &variant.fields {
308                         if let ty::FnDef(..) = field.ty(cx.tcx, substs).kind() {
309                             return;
310                         }
311                     }
312                     for subst in substs {
313                         if let ty::subst::GenericArgKind::Type(subst) = subst.unpack() {
314                             if let ty::Param(_) = subst.kind() {
315                                 return;
316                             }
317                         }
318                     }
319                 }
320             },
321             _ => (),
322         }
323
324         span_lint_and_note(
325             cx,
326             EXPL_IMPL_CLONE_ON_COPY,
327             item.span,
328             "you are implementing `Clone` explicitly on a `Copy` type",
329             Some(item.span),
330             "consider deriving `Clone` or removing `Copy`",
331         );
332     }
333 }
334
335 /// Implementation of the `UNSAFE_DERIVE_DESERIALIZE` lint.
336 fn check_unsafe_derive_deserialize<'tcx>(
337     cx: &LateContext<'tcx>,
338     item: &Item<'_>,
339     trait_ref: &TraitRef<'_>,
340     ty: Ty<'tcx>,
341 ) {
342     fn item_from_def_id<'tcx>(cx: &LateContext<'tcx>, def_id: DefId) -> &'tcx Item<'tcx> {
343         let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
344         cx.tcx.hir().expect_item(hir_id)
345     }
346
347     fn has_unsafe<'tcx>(cx: &LateContext<'tcx>, item: &'tcx Item<'_>) -> bool {
348         let mut visitor = UnsafeVisitor { cx, has_unsafe: false };
349         walk_item(&mut visitor, item);
350         visitor.has_unsafe
351     }
352
353     if_chain! {
354         if let Some(trait_def_id) = trait_ref.trait_def_id();
355         if match_def_path(cx, trait_def_id, &paths::SERDE_DESERIALIZE);
356         if let ty::Adt(def, _) = ty.kind();
357         if let Some(local_def_id) = def.did.as_local();
358         let adt_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);
359         if !is_allowed(cx, UNSAFE_DERIVE_DESERIALIZE, adt_hir_id);
360         if cx.tcx.inherent_impls(def.did)
361             .iter()
362             .map(|imp_did| item_from_def_id(cx, *imp_did))
363             .any(|imp| has_unsafe(cx, imp));
364         then {
365             span_lint_and_help(
366                 cx,
367                 UNSAFE_DERIVE_DESERIALIZE,
368                 item.span,
369                 "you are deriving `serde::Deserialize` on a type that has methods using `unsafe`",
370                 None,
371                 "consider implementing `serde::Deserialize` manually. See https://serde.rs/impl-deserialize.html"
372             );
373         }
374     }
375 }
376
377 struct UnsafeVisitor<'a, 'tcx> {
378     cx: &'a LateContext<'tcx>,
379     has_unsafe: bool,
380 }
381
382 impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> {
383     type Map = Map<'tcx>;
384
385     fn visit_fn(&mut self, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'_>, body_id: BodyId, span: Span, id: HirId) {
386         if self.has_unsafe {
387             return;
388         }
389
390         if_chain! {
391             if let Some(header) = kind.header();
392             if let Unsafety::Unsafe = header.unsafety;
393             then {
394                 self.has_unsafe = true;
395             }
396         }
397
398         walk_fn(self, kind, decl, body_id, span, id);
399     }
400
401     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
402         if self.has_unsafe {
403             return;
404         }
405
406         if let ExprKind::Block(block, _) = expr.kind {
407             match block.rules {
408                 BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided)
409                 | BlockCheckMode::PushUnsafeBlock(UnsafeSource::UserProvided)
410                 | BlockCheckMode::PopUnsafeBlock(UnsafeSource::UserProvided) => {
411                     self.has_unsafe = true;
412                 },
413                 _ => {},
414             }
415         }
416
417         walk_expr(self, expr);
418     }
419
420     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
421         NestedVisitorMap::All(self.cx.tcx.hir())
422     }
423 }