1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::{def_path_def_ids, trait_ref_of_method};
3 use rustc_data_structures::fx::FxHashSet;
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_middle::ty::TypeVisitable;
7 use rustc_middle::ty::{Adt, Array, Ref, Slice, Tuple, Ty};
8 use rustc_session::{declare_tool_lint, impl_lint_pass};
9 use rustc_span::source_map::Span;
10 use rustc_span::symbol::sym;
13 declare_clippy_lint! {
15 /// Checks for sets/maps with mutable key types.
17 /// ### Why is this bad?
18 /// All of `HashMap`, `HashSet`, `BTreeMap` and
19 /// `BtreeSet` rely on either the hash or the order of keys be unchanging,
20 /// so having types with interior mutability is a bad idea.
22 /// ### Known problems
24 /// #### False Positives
25 /// It's correct to use a struct that contains interior mutability as a key, when its
26 /// implementation of `Hash` or `Ord` doesn't access any of the interior mutable types.
27 /// However, this lint is unable to recognize this, so it will often cause false positives in
28 /// theses cases. The `bytes` crate is a great example of this.
30 /// #### False Negatives
31 /// For custom `struct`s/`enum`s, this lint is unable to check for interior mutability behind
32 /// indirection. For example, `struct BadKey<'a>(&'a Cell<usize>)` will be seen as immutable
33 /// and cause a false negative if its implementation of `Hash`/`Ord` accesses the `Cell`.
35 /// This lint does check a few cases for indirection. Firstly, using some standard library
36 /// types (`Option`, `Result`, `Box`, `Rc`, `Arc`, `Vec`, `VecDeque`, `BTreeMap` and
37 /// `BTreeSet`) directly as keys (e.g. in `HashMap<Box<Cell<usize>>, ()>`) **will** trigger the
38 /// lint, because the impls of `Hash`/`Ord` for these types directly call `Hash`/`Ord` on their
41 /// Secondly, the implementations of `Hash` and `Ord` for raw pointers (`*const T` or `*mut T`)
42 /// apply only to the **address** of the contained value. Therefore, interior mutability
43 /// behind raw pointers (e.g. in `HashSet<*mut Cell<usize>>`) can't impact the value of `Hash`
44 /// or `Ord`, and therefore will not trigger this link. For more info, see issue
45 /// [#6745](https://github.com/rust-lang/rust-clippy/issues/6745).
49 /// use std::cmp::{PartialEq, Eq};
50 /// use std::collections::HashSet;
51 /// use std::hash::{Hash, Hasher};
52 /// use std::sync::atomic::AtomicUsize;
55 /// struct Bad(AtomicUsize);
56 /// impl PartialEq for Bad {
57 /// fn eq(&self, rhs: &Self) -> bool {
59 /// ; unimplemented!();
63 /// impl Eq for Bad {}
65 /// impl Hash for Bad {
66 /// fn hash<H: Hasher>(&self, h: &mut H) {
68 /// ; unimplemented!();
73 /// let _: HashSet<Bad> = HashSet::new();
76 #[clippy::version = "1.42.0"]
79 "Check for mutable `Map`/`Set` key type"
83 pub struct MutableKeyType {
84 ignore_interior_mutability: Vec<String>,
85 ignore_mut_def_ids: FxHashSet<hir::def_id::DefId>,
88 impl_lint_pass!(MutableKeyType => [ MUTABLE_KEY_TYPE ]);
90 impl<'tcx> LateLintPass<'tcx> for MutableKeyType {
91 fn check_crate(&mut self, cx: &LateContext<'tcx>) {
92 self.ignore_mut_def_ids.clear();
93 let mut path = Vec::new();
94 for ty in &self.ignore_interior_mutability {
95 path.extend(ty.split("::"));
96 for id in def_path_def_ids(cx, &path[..]) {
97 self.ignore_mut_def_ids.insert(id);
103 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
104 if let hir::ItemKind::Fn(ref sig, ..) = item.kind {
105 self.check_sig(cx, item.hir_id(), sig.decl);
109 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'tcx>) {
110 if let hir::ImplItemKind::Fn(ref sig, ..) = item.kind {
111 if trait_ref_of_method(cx, item.owner_id.def_id).is_none() {
112 self.check_sig(cx, item.hir_id(), sig.decl);
117 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'tcx>) {
118 if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
119 self.check_sig(cx, item.hir_id(), sig.decl);
123 fn check_local(&mut self, cx: &LateContext<'_>, local: &hir::Local<'_>) {
124 if let hir::PatKind::Wild = local.pat.kind {
127 self.check_ty_(cx, local.span, cx.typeck_results().pat_ty(local.pat));
131 impl MutableKeyType {
132 pub fn new(ignore_interior_mutability: Vec<String>) -> Self {
134 ignore_interior_mutability,
135 ignore_mut_def_ids: FxHashSet::default(),
139 fn check_sig(&self, cx: &LateContext<'_>, item_hir_id: hir::HirId, decl: &hir::FnDecl<'_>) {
140 let fn_def_id = cx.tcx.hir().local_def_id(item_hir_id);
141 let fn_sig = cx.tcx.fn_sig(fn_def_id);
142 for (hir_ty, ty) in iter::zip(decl.inputs, fn_sig.inputs().skip_binder()) {
143 self.check_ty_(cx, hir_ty.span, *ty);
145 self.check_ty_(cx, decl.output.span(), cx.tcx.erase_late_bound_regions(fn_sig.output()));
148 // We want to lint 1. sets or maps with 2. not immutable key types and 3. no unerased
149 // generics (because the compiler cannot ensure immutability for unknown types).
150 fn check_ty_<'tcx>(&self, cx: &LateContext<'tcx>, span: Span, ty: Ty<'tcx>) {
151 let ty = ty.peel_refs();
152 if let Adt(def, substs) = ty.kind() {
153 let is_keyed_type = [sym::HashMap, sym::BTreeMap, sym::HashSet, sym::BTreeSet]
155 .any(|diag_item| cx.tcx.is_diagnostic_item(*diag_item, def.did()));
156 if is_keyed_type && self.is_interior_mutable_type(cx, substs.type_at(0)) {
157 span_lint(cx, MUTABLE_KEY_TYPE, span, "mutable key type");
162 /// Determines if a type contains interior mutability which would affect its implementation of
163 /// [`Hash`] or [`Ord`].
164 fn is_interior_mutable_type<'tcx>(&self, cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
166 Ref(_, inner_ty, mutbl) => mutbl == hir::Mutability::Mut || self.is_interior_mutable_type(cx, inner_ty),
167 Slice(inner_ty) => self.is_interior_mutable_type(cx, inner_ty),
168 Array(inner_ty, size) => {
169 size.try_eval_usize(cx.tcx, cx.param_env).map_or(true, |u| u != 0)
170 && self.is_interior_mutable_type(cx, inner_ty)
172 Tuple(fields) => fields.iter().any(|ty| self.is_interior_mutable_type(cx, ty)),
173 Adt(def, substs) => {
174 // Special case for collections in `std` who's impl of `Hash` or `Ord` delegates to
175 // that of their type parameters. Note: we don't include `HashSet` and `HashMap`
176 // because they have no impl for `Hash` or `Ord`.
177 let def_id = def.did();
178 let is_std_collection = [
190 .any(|diag_item| cx.tcx.is_diagnostic_item(*diag_item, def_id));
191 let is_box = Some(def_id) == cx.tcx.lang_items().owned_box();
192 if is_std_collection || is_box || self.ignore_mut_def_ids.contains(&def_id) {
193 // The type is mutable if any of its type parameters are
194 substs.types().any(|ty| self.is_interior_mutable_type(cx, ty))
196 !ty.has_escaping_bound_vars()
197 && cx.tcx.layout_of(cx.param_env.and(ty)).is_ok()
198 && !ty.is_freeze(cx.tcx, cx.param_env)