]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/mut_key.rs
Merge commit '4911ab124c481430672a3833b37075e6435ec34d' into clippyup
[rust.git] / clippy_lints / src / mut_key.rs
1 use crate::utils::{match_def_path, paths, span_lint, trait_ref_of_method};
2 use rustc_hir as hir;
3 use rustc_lint::{LateContext, LateLintPass};
4 use rustc_middle::ty::TypeFoldable;
5 use rustc_middle::ty::{Adt, Array, RawPtr, Ref, Slice, Tuple, Ty, TypeAndMut};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7 use rustc_span::source_map::Span;
8
9 declare_clippy_lint! {
10     /// **What it does:** Checks for sets/maps with mutable key types.
11     ///
12     /// **Why is this bad?** All of `HashMap`, `HashSet`, `BTreeMap` and
13     /// `BtreeSet` rely on either the hash or the order of keys be unchanging,
14     /// so having types with interior mutability is a bad idea.
15     ///
16     /// **Known problems:** It's correct to use a struct, that contains interior mutability
17     /// as a key, when its `Hash` implementation doesn't access any of the interior mutable types.
18     /// However, this lint is unable to recognize this, so it causes a false positive in theses cases.
19     /// The `bytes` crate is a great example of this.
20     ///
21     /// **Example:**
22     /// ```rust
23     /// use std::cmp::{PartialEq, Eq};
24     /// use std::collections::HashSet;
25     /// use std::hash::{Hash, Hasher};
26     /// use std::sync::atomic::AtomicUsize;
27     ///# #[allow(unused)]
28     ///
29     /// struct Bad(AtomicUsize);
30     /// impl PartialEq for Bad {
31     ///     fn eq(&self, rhs: &Self) -> bool {
32     ///          ..
33     /// ; unimplemented!();
34     ///     }
35     /// }
36     ///
37     /// impl Eq for Bad {}
38     ///
39     /// impl Hash for Bad {
40     ///     fn hash<H: Hasher>(&self, h: &mut H) {
41     ///         ..
42     /// ; unimplemented!();
43     ///     }
44     /// }
45     ///
46     /// fn main() {
47     ///     let _: HashSet<Bad> = HashSet::new();
48     /// }
49     /// ```
50     pub MUTABLE_KEY_TYPE,
51     correctness,
52     "Check for mutable `Map`/`Set` key type"
53 }
54
55 declare_lint_pass!(MutableKeyType => [ MUTABLE_KEY_TYPE ]);
56
57 impl<'tcx> LateLintPass<'tcx> for MutableKeyType {
58     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
59         if let hir::ItemKind::Fn(ref sig, ..) = item.kind {
60             check_sig(cx, item.hir_id, &sig.decl);
61         }
62     }
63
64     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'tcx>) {
65         if let hir::ImplItemKind::Fn(ref sig, ..) = item.kind {
66             if trait_ref_of_method(cx, item.hir_id).is_none() {
67                 check_sig(cx, item.hir_id, &sig.decl);
68             }
69         }
70     }
71
72     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'tcx>) {
73         if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
74             check_sig(cx, item.hir_id, &sig.decl);
75         }
76     }
77
78     fn check_local(&mut self, cx: &LateContext<'_>, local: &hir::Local<'_>) {
79         if let hir::PatKind::Wild = local.pat.kind {
80             return;
81         }
82         check_ty(cx, local.span, cx.typeck_results().pat_ty(&*local.pat));
83     }
84 }
85
86 fn check_sig<'tcx>(cx: &LateContext<'tcx>, item_hir_id: hir::HirId, decl: &hir::FnDecl<'_>) {
87     let fn_def_id = cx.tcx.hir().local_def_id(item_hir_id);
88     let fn_sig = cx.tcx.fn_sig(fn_def_id);
89     for (hir_ty, ty) in decl.inputs.iter().zip(fn_sig.inputs().skip_binder().iter()) {
90         check_ty(cx, hir_ty.span, ty);
91     }
92     check_ty(cx, decl.output.span(), cx.tcx.erase_late_bound_regions(fn_sig.output()));
93 }
94
95 // We want to lint 1. sets or maps with 2. not immutable key types and 3. no unerased
96 // generics (because the compiler cannot ensure immutability for unknown types).
97 fn check_ty<'tcx>(cx: &LateContext<'tcx>, span: Span, ty: Ty<'tcx>) {
98     let ty = ty.peel_refs();
99     if let Adt(def, substs) = ty.kind() {
100         if [&paths::HASHMAP, &paths::BTREEMAP, &paths::HASHSET, &paths::BTREESET]
101             .iter()
102             .any(|path| match_def_path(cx, def.did, &**path))
103             && is_mutable_type(cx, substs.type_at(0), span)
104         {
105             span_lint(cx, MUTABLE_KEY_TYPE, span, "mutable key type");
106         }
107     }
108 }
109
110 fn is_mutable_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, span: Span) -> bool {
111     match *ty.kind() {
112         RawPtr(TypeAndMut { ty: inner_ty, mutbl }) | Ref(_, inner_ty, mutbl) => {
113             mutbl == hir::Mutability::Mut || is_mutable_type(cx, inner_ty, span)
114         },
115         Slice(inner_ty) => is_mutable_type(cx, inner_ty, span),
116         Array(inner_ty, size) => {
117             size.try_eval_usize(cx.tcx, cx.param_env).map_or(true, |u| u != 0) && is_mutable_type(cx, inner_ty, span)
118         },
119         Tuple(..) => ty.tuple_fields().any(|ty| is_mutable_type(cx, ty, span)),
120         Adt(..) => {
121             cx.tcx.layout_of(cx.param_env.and(ty)).is_ok()
122                 && !ty.has_escaping_bound_vars()
123                 && !ty.is_freeze(cx.tcx.at(span), cx.param_env)
124         },
125         _ => false,
126     }
127 }