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