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