2021-03-25 13:29:11 -05:00
|
|
|
use clippy_utils::diagnostics::span_lint;
|
2021-07-29 05:16:06 -05:00
|
|
|
use clippy_utils::trait_ref_of_method;
|
2020-01-06 10:39:50 -06:00
|
|
|
use rustc_hir as hir;
|
2020-01-12 00:08:41 -06:00
|
|
|
use rustc_lint::{LateContext, LateLintPass};
|
2022-06-17 07:15:00 -05:00
|
|
|
use rustc_middle::ty::TypeVisitable;
|
2021-09-28 12:03:12 -05:00
|
|
|
use rustc_middle::ty::{Adt, Array, Ref, Slice, Tuple, Ty};
|
2020-01-11 05:37:08 -06:00
|
|
|
use rustc_session::{declare_lint_pass, declare_tool_lint};
|
2020-01-04 04:00:00 -06:00
|
|
|
use rustc_span::source_map::Span;
|
2021-07-29 05:16:06 -05:00
|
|
|
use rustc_span::symbol::sym;
|
2021-03-08 17:57:44 -06:00
|
|
|
use std::iter;
|
2019-12-06 12:45:33 -06:00
|
|
|
|
|
|
|
declare_clippy_lint! {
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### What it does
|
|
|
|
/// Checks for sets/maps with mutable key types.
|
2019-12-06 12:45:33 -06:00
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// All of `HashMap`, `HashSet`, `BTreeMap` and
|
2019-12-06 12:45:33 -06:00
|
|
|
/// `BtreeSet` rely on either the hash or the order of keys be unchanging,
|
|
|
|
/// so having types with interior mutability is a bad idea.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Known problems
|
2021-09-28 12:03:12 -05:00
|
|
|
///
|
|
|
|
/// #### False Positives
|
|
|
|
/// 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
|
|
|
|
/// theses cases. The `bytes` crate is a great example of this.
|
|
|
|
///
|
|
|
|
/// #### False Negatives
|
|
|
|
/// For custom `struct`s/`enum`s, this lint is unable to check for interior mutability behind
|
|
|
|
/// indirection. For example, `struct BadKey<'a>(&'a Cell<usize>)` will be seen as immutable
|
|
|
|
/// and cause a false negative if its implementation of `Hash`/`Ord` accesses the `Cell`.
|
|
|
|
///
|
|
|
|
/// This lint does check a few cases for indirection. Firstly, using some standard library
|
|
|
|
/// types (`Option`, `Result`, `Box`, `Rc`, `Arc`, `Vec`, `VecDeque`, `BTreeMap` and
|
|
|
|
/// `BTreeSet`) directly as keys (e.g. in `HashMap<Box<Cell<usize>>, ()>`) **will** trigger the
|
|
|
|
/// lint, because the impls of `Hash`/`Ord` for these types directly call `Hash`/`Ord` on their
|
|
|
|
/// contained type.
|
|
|
|
///
|
|
|
|
/// Secondly, the implementations of `Hash` and `Ord` for raw pointers (`*const T` or `*mut T`)
|
|
|
|
/// apply only to the **address** of the contained value. Therefore, interior mutability
|
|
|
|
/// behind raw pointers (e.g. in `HashSet<*mut Cell<usize>>`) can't impact the value of `Hash`
|
|
|
|
/// or `Ord`, and therefore will not trigger this link. For more info, see issue
|
|
|
|
/// [#6745](https://github.com/rust-lang/rust-clippy/issues/6745).
|
2019-12-06 12:45:33 -06:00
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Example
|
2019-12-06 12:45:33 -06:00
|
|
|
/// ```rust
|
|
|
|
/// use std::cmp::{PartialEq, Eq};
|
|
|
|
/// use std::collections::HashSet;
|
|
|
|
/// use std::hash::{Hash, Hasher};
|
|
|
|
/// use std::sync::atomic::AtomicUsize;
|
|
|
|
///# #[allow(unused)]
|
|
|
|
///
|
|
|
|
/// struct Bad(AtomicUsize);
|
|
|
|
/// impl PartialEq for Bad {
|
|
|
|
/// fn eq(&self, rhs: &Self) -> bool {
|
|
|
|
/// ..
|
|
|
|
/// ; unimplemented!();
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// impl Eq for Bad {}
|
|
|
|
///
|
|
|
|
/// impl Hash for Bad {
|
|
|
|
/// fn hash<H: Hasher>(&self, h: &mut H) {
|
|
|
|
/// ..
|
|
|
|
/// ; unimplemented!();
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// let _: HashSet<Bad> = HashSet::new();
|
|
|
|
/// }
|
|
|
|
/// ```
|
2021-12-06 05:33:31 -06:00
|
|
|
#[clippy::version = "1.42.0"]
|
2019-12-06 12:45:33 -06:00
|
|
|
pub MUTABLE_KEY_TYPE,
|
2021-07-01 11:17:38 -05:00
|
|
|
suspicious,
|
2020-01-06 00:30:43 -06:00
|
|
|
"Check for mutable `Map`/`Set` key type"
|
2019-12-06 12:45:33 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
declare_lint_pass!(MutableKeyType => [ MUTABLE_KEY_TYPE ]);
|
|
|
|
|
2020-06-25 15:41:36 -05:00
|
|
|
impl<'tcx> LateLintPass<'tcx> for MutableKeyType {
|
|
|
|
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
|
2019-12-06 12:45:33 -06:00
|
|
|
if let hir::ItemKind::Fn(ref sig, ..) = item.kind {
|
2021-04-08 10:50:13 -05:00
|
|
|
check_sig(cx, item.hir_id(), sig.decl);
|
2019-12-06 12:45:33 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-25 15:41:36 -05:00
|
|
|
fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'tcx>) {
|
2020-03-16 10:00:16 -05:00
|
|
|
if let hir::ImplItemKind::Fn(ref sig, ..) = item.kind {
|
2022-10-26 22:02:18 -05:00
|
|
|
if trait_ref_of_method(cx, item.owner_id.def_id).is_none() {
|
2021-04-08 10:50:13 -05:00
|
|
|
check_sig(cx, item.hir_id(), sig.decl);
|
2019-12-06 12:45:33 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-25 15:41:36 -05:00
|
|
|
fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'tcx>) {
|
2020-03-12 14:56:55 -05:00
|
|
|
if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
|
2021-04-08 10:50:13 -05:00
|
|
|
check_sig(cx, item.hir_id(), sig.decl);
|
2019-12-06 12:45:33 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-25 15:41:36 -05:00
|
|
|
fn check_local(&mut self, cx: &LateContext<'_>, local: &hir::Local<'_>) {
|
2019-12-06 12:45:33 -06:00
|
|
|
if let hir::PatKind::Wild = local.pat.kind {
|
|
|
|
return;
|
|
|
|
}
|
2022-06-04 06:34:07 -05:00
|
|
|
check_ty(cx, local.span, cx.typeck_results().pat_ty(local.pat));
|
2019-12-06 12:45:33 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-25 15:41:36 -05:00
|
|
|
fn check_sig<'tcx>(cx: &LateContext<'tcx>, item_hir_id: hir::HirId, decl: &hir::FnDecl<'_>) {
|
2019-12-06 12:45:33 -06:00
|
|
|
let fn_def_id = cx.tcx.hir().local_def_id(item_hir_id);
|
|
|
|
let fn_sig = cx.tcx.fn_sig(fn_def_id);
|
2021-03-08 17:57:44 -06:00
|
|
|
for (hir_ty, ty) in iter::zip(decl.inputs, fn_sig.inputs().skip_binder()) {
|
Overhaul `TyS` and `Ty`.
Specifically, change `Ty` from this:
```
pub type Ty<'tcx> = &'tcx TyS<'tcx>;
```
to this
```
pub struct Ty<'tcx>(Interned<'tcx, TyS<'tcx>>);
```
There are two benefits to this.
- It's now a first class type, so we can define methods on it. This
means we can move a lot of methods away from `TyS`, leaving `TyS` as a
barely-used type, which is appropriate given that it's not meant to
be used directly.
- The uniqueness requirement is now explicit, via the `Interned` type.
E.g. the pointer-based `Eq` and `Hash` comes from `Interned`, rather
than via `TyS`, which wasn't obvious at all.
Much of this commit is boring churn. The interesting changes are in
these files:
- compiler/rustc_middle/src/arena.rs
- compiler/rustc_middle/src/mir/visit.rs
- compiler/rustc_middle/src/ty/context.rs
- compiler/rustc_middle/src/ty/mod.rs
Specifically:
- Most mentions of `TyS` are removed. It's very much a dumb struct now;
`Ty` has all the smarts.
- `TyS` now has `crate` visibility instead of `pub`.
- `TyS::make_for_test` is removed in favour of the static `BOOL_TY`,
which just works better with the new structure.
- The `Eq`/`Ord`/`Hash` impls are removed from `TyS`. `Interned`s impls
of `Eq`/`Hash` now suffice. `Ord` is now partly on `Interned`
(pointer-based, for the `Equal` case) and partly on `TyS`
(contents-based, for the other cases).
- There are many tedious sigil adjustments, i.e. adding or removing `*`
or `&`. They seem to be unavoidable.
2022-01-24 21:13:38 -06:00
|
|
|
check_ty(cx, hir_ty.span, *ty);
|
2019-12-06 12:45:33 -06:00
|
|
|
}
|
2020-11-23 06:51:04 -06:00
|
|
|
check_ty(cx, decl.output.span(), cx.tcx.erase_late_bound_regions(fn_sig.output()));
|
2019-12-06 12:45:33 -06: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).
|
2020-06-25 15:41:36 -05:00
|
|
|
fn check_ty<'tcx>(cx: &LateContext<'tcx>, span: Span, ty: Ty<'tcx>) {
|
2020-09-24 07:49:22 -05:00
|
|
|
let ty = ty.peel_refs();
|
2020-08-03 17:18:29 -05:00
|
|
|
if let Adt(def, substs) = ty.kind() {
|
2021-10-02 18:51:01 -05:00
|
|
|
let is_keyed_type = [sym::HashMap, sym::BTreeMap, sym::HashSet, sym::BTreeSet]
|
2019-12-06 12:45:33 -06:00
|
|
|
.iter()
|
2022-03-04 14:28:41 -06:00
|
|
|
.any(|diag_item| cx.tcx.is_diagnostic_item(*diag_item, def.did()));
|
2021-09-28 12:03:12 -05:00
|
|
|
if is_keyed_type && is_interior_mutable_type(cx, substs.type_at(0), span) {
|
2020-01-16 17:18:37 -06:00
|
|
|
span_lint(cx, MUTABLE_KEY_TYPE, span, "mutable key type");
|
2019-12-06 12:45:33 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-28 12:03:12 -05:00
|
|
|
/// Determines if a type contains interior mutability which would affect its implementation of
|
|
|
|
/// [`Hash`] or [`Ord`].
|
|
|
|
fn is_interior_mutable_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, span: Span) -> bool {
|
2020-08-03 17:18:29 -05:00
|
|
|
match *ty.kind() {
|
2022-10-27 09:32:17 -05:00
|
|
|
Ref(_, inner_ty, mutbl) => {
|
|
|
|
mutbl == hir::Mutability::Mut || is_interior_mutable_type(cx, inner_ty, span)
|
|
|
|
}
|
2021-09-28 12:03:12 -05:00
|
|
|
Slice(inner_ty) => is_interior_mutable_type(cx, inner_ty, span),
|
2020-01-16 17:18:37 -06:00
|
|
|
Array(inner_ty, size) => {
|
2021-09-28 12:03:12 -05:00
|
|
|
size.try_eval_usize(cx.tcx, cx.param_env).map_or(true, |u| u != 0)
|
|
|
|
&& is_interior_mutable_type(cx, inner_ty, span)
|
2022-10-27 09:32:17 -05:00
|
|
|
}
|
2022-02-07 09:06:55 -06:00
|
|
|
Tuple(fields) => fields.iter().any(|ty| is_interior_mutable_type(cx, ty, span)),
|
2021-09-28 12:03:12 -05:00
|
|
|
Adt(def, substs) => {
|
|
|
|
// Special case for collections in `std` who's impl of `Hash` or `Ord` delegates to
|
|
|
|
// that of their type parameters. Note: we don't include `HashSet` and `HashMap`
|
|
|
|
// because they have no impl for `Hash` or `Ord`.
|
|
|
|
let is_std_collection = [
|
2021-10-02 18:51:01 -05:00
|
|
|
sym::Option,
|
|
|
|
sym::Result,
|
2021-09-28 12:03:12 -05:00
|
|
|
sym::LinkedList,
|
2021-10-02 18:51:01 -05:00
|
|
|
sym::Vec,
|
|
|
|
sym::VecDeque,
|
2021-09-28 12:03:12 -05:00
|
|
|
sym::BTreeMap,
|
|
|
|
sym::BTreeSet,
|
|
|
|
sym::Rc,
|
|
|
|
sym::Arc,
|
|
|
|
]
|
|
|
|
.iter()
|
2022-03-04 14:28:41 -06:00
|
|
|
.any(|diag_item| cx.tcx.is_diagnostic_item(*diag_item, def.did()));
|
|
|
|
let is_box = Some(def.did()) == cx.tcx.lang_items().owned_box();
|
2021-09-28 12:03:12 -05:00
|
|
|
if is_std_collection || is_box {
|
|
|
|
// The type is mutable if any of its type parameters are
|
|
|
|
substs.types().any(|ty| is_interior_mutable_type(cx, ty, span))
|
|
|
|
} else {
|
|
|
|
!ty.has_escaping_bound_vars()
|
|
|
|
&& cx.tcx.layout_of(cx.param_env.and(ty)).is_ok()
|
2022-10-27 09:32:17 -05:00
|
|
|
&& !ty.is_freeze(cx.tcx, cx.param_env)
|
2021-09-28 12:03:12 -05:00
|
|
|
}
|
2022-10-27 09:32:17 -05:00
|
|
|
}
|
2020-01-16 17:18:37 -06:00
|
|
|
_ => false,
|
2019-12-06 12:45:33 -06:00
|
|
|
}
|
|
|
|
}
|