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