rust/clippy_lints/src/mut_key.rs

148 lines
5.0 KiB
Rust
Raw Normal View History

use clippy_utils::diagnostics::span_lint;
2024-04-18 17:05:07 +00:00
use clippy_utils::trait_ref_of_method;
use clippy_utils::ty::InteriorMut;
2020-01-07 01:39:50 +09:00
use rustc_hir as hir;
2020-01-12 15:08:41 +09:00
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::{self, Ty};
use rustc_session::impl_lint_pass;
use rustc_span::def_id::LocalDefId;
use rustc_span::symbol::sym;
use rustc_span::Span;
2021-03-08 15:57:44 -08:00
use std::iter;
2019-12-06 19:45:33 +01:00
declare_clippy_lint! {
/// ### What it does
/// Checks for sets/maps with mutable key types.
2019-12-06 19:45:33 +01:00
///
/// ### Why is this bad?
/// All of `HashMap`, `HashSet`, `BTreeMap` and
2019-12-06 19:45:33 +01:00
/// `BtreeSet` rely on either the hash or the order of keys be unchanging,
/// so having types with interior mutability is a bad idea.
///
/// ### Known problems
///
/// #### False Positives
2024-04-18 17:05:07 +00:00
/// It's correct to use a struct that contains interior mutability as a key when its
/// implementation of `Hash` or `Ord` doesn't access any of the interior mutable types.
/// However, this lint is unable to recognize this, so it will often cause false positives in
2024-04-18 17:05:07 +00:00
/// these cases.
///
/// #### False Negatives
2024-04-18 17:05:07 +00:00
/// This lint does not follow raw pointers (`*const T` or `*mut T`) as `Hash` and `Ord`
/// apply only to the **address** of the contained value. This can cause false negatives for
/// custom collections that use raw pointers internally.
2019-12-06 19:45:33 +01:00
///
/// ### Example
/// ```no_run
2019-12-06 19:45:33 +01:00
/// use std::cmp::{PartialEq, Eq};
/// use std::collections::HashSet;
/// use std::hash::{Hash, Hasher};
/// use std::sync::atomic::AtomicUsize;
///
/// struct Bad(AtomicUsize);
/// impl PartialEq for Bad {
/// fn eq(&self, rhs: &Self) -> bool {
/// ..
2024-04-18 17:05:07 +00:00
/// # ; true
2019-12-06 19:45:33 +01:00
/// }
/// }
///
/// impl Eq for Bad {}
///
/// impl Hash for Bad {
/// fn hash<H: Hasher>(&self, h: &mut H) {
/// ..
2024-04-18 17:05:07 +00:00
/// # ;
2019-12-06 19:45:33 +01:00
/// }
/// }
///
/// fn main() {
/// let _: HashSet<Bad> = HashSet::new();
/// }
/// ```
#[clippy::version = "1.42.0"]
2019-12-06 19:45:33 +01:00
pub MUTABLE_KEY_TYPE,
suspicious,
2020-01-06 15:30:43 +09:00
"Check for mutable `Map`/`Set` key type"
2019-12-06 19:45:33 +01:00
}
2024-04-18 17:05:07 +00:00
pub struct MutableKeyType<'tcx> {
ignore_interior_mutability: Vec<String>,
2024-04-18 17:05:07 +00:00
interior_mut: InteriorMut<'tcx>,
}
2024-04-18 17:05:07 +00:00
impl_lint_pass!(MutableKeyType<'_> => [ MUTABLE_KEY_TYPE ]);
2019-12-06 19:45:33 +01:00
2024-04-18 17:05:07 +00:00
impl<'tcx> LateLintPass<'tcx> for MutableKeyType<'tcx> {
fn check_crate(&mut self, cx: &LateContext<'tcx>) {
2024-04-18 17:05:07 +00:00
self.interior_mut = InteriorMut::without_pointers(cx, &self.ignore_interior_mutability);
}
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
2019-12-06 19:45:33 +01:00
if let hir::ItemKind::Fn(ref sig, ..) = item.kind {
self.check_sig(cx, item.owner_id.def_id, sig.decl);
2019-12-06 19:45:33 +01:00
}
}
fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'tcx>) {
if let hir::ImplItemKind::Fn(ref sig, ..) = item.kind {
if trait_ref_of_method(cx, item.owner_id.def_id).is_none() {
self.check_sig(cx, item.owner_id.def_id, sig.decl);
2019-12-06 19:45:33 +01:00
}
}
}
fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'tcx>) {
2020-03-13 04:56:55 +09:00
if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
self.check_sig(cx, item.owner_id.def_id, sig.decl);
2019-12-06 19:45:33 +01:00
}
}
2024-04-18 17:05:07 +00:00
fn check_local(&mut self, cx: &LateContext<'tcx>, local: &hir::LetStmt<'tcx>) {
2019-12-06 19:45:33 +01:00
if let hir::PatKind::Wild = local.pat.kind {
return;
}
self.check_ty_(cx, local.span, cx.typeck_results().pat_ty(local.pat));
2019-12-06 19:45:33 +01:00
}
}
2024-04-18 17:05:07 +00:00
impl<'tcx> MutableKeyType<'tcx> {
pub fn new(ignore_interior_mutability: Vec<String>) -> Self {
Self {
ignore_interior_mutability,
2024-04-18 17:05:07 +00:00
interior_mut: InteriorMut::default(),
}
2019-12-06 19:45:33 +01:00
}
2024-04-18 17:05:07 +00:00
fn check_sig(&mut self, cx: &LateContext<'tcx>, fn_def_id: LocalDefId, decl: &hir::FnDecl<'tcx>) {
let fn_sig = cx.tcx.fn_sig(fn_def_id).instantiate_identity();
for (hir_ty, ty) in iter::zip(decl.inputs, fn_sig.inputs().skip_binder()) {
self.check_ty_(cx, hir_ty.span, *ty);
2019-12-06 19:45:33 +01:00
}
self.check_ty_(
cx,
decl.output.span(),
cx.tcx.instantiate_bound_regions_with_erased(fn_sig.output()),
);
2019-12-06 19:45:33 +01:00
}
// We want to lint 1. sets or maps with 2. not immutable key types and 3. no unerased
// generics (because the compiler cannot ensure immutability for unknown types).
2024-04-18 17:05:07 +00:00
fn check_ty_(&mut self, cx: &LateContext<'tcx>, span: Span, ty: Ty<'tcx>) {
let ty = ty.peel_refs();
if let ty::Adt(def, args) = ty.kind() {
let is_keyed_type = [sym::HashMap, sym::BTreeMap, sym::HashSet, sym::BTreeSet]
.iter()
.any(|diag_item| cx.tcx.is_diagnostic_item(*diag_item, def.did()));
if !is_keyed_type {
return;
}
let subst_ty = args.type_at(0);
2024-04-18 17:05:07 +00:00
if self.interior_mut.is_interior_mut_ty(cx, subst_ty) {
span_lint(cx, MUTABLE_KEY_TYPE, span, "mutable key type");
}
}
2019-12-06 19:45:33 +01:00
}
}