2023-04-23 11:03:09 +00:00
|
|
|
//! Checks for usage of const which the type is not `Freeze` (`Cell`-free).
|
2018-06-06 15:20:22 +00:00
|
|
|
//!
|
2020-10-09 10:45:29 +00:00
|
|
|
//! This lint is **warn** by default.
|
2018-06-06 15:20:22 +00:00
|
|
|
|
2019-01-31 01:15:29 +00:00
|
|
|
use std::ptr;
|
|
|
|
|
2021-03-25 18:29:11 +00:00
|
|
|
use clippy_utils::diagnostics::span_lint_and_then;
|
|
|
|
use clippy_utils::in_constant;
|
2022-06-30 08:50:09 +00:00
|
|
|
use clippy_utils::macros::macro_backtrace;
|
2021-03-25 18:29:11 +00:00
|
|
|
use if_chain::if_chain;
|
2020-01-06 16:39:50 +00:00
|
|
|
use rustc_hir::def::{DefKind, Res};
|
2020-11-23 12:51:04 +00:00
|
|
|
use rustc_hir::def_id::DefId;
|
|
|
|
use rustc_hir::{
|
2020-11-22 22:46:21 +00:00
|
|
|
BodyId, Expr, ExprKind, HirId, Impl, ImplItem, ImplItemKind, Item, ItemKind, Node, TraitItem, TraitItemKind, UnOp,
|
2020-11-23 12:51:04 +00:00
|
|
|
};
|
2022-10-06 07:44:38 +00:00
|
|
|
use rustc_hir_analysis::hir_ty_to_ty;
|
2020-01-12 06:08:41 +00:00
|
|
|
use rustc_lint::{LateContext, LateLintPass, Lint};
|
2023-06-16 16:02:11 +00:00
|
|
|
use rustc_middle::mir::interpret::ErrorHandled;
|
2020-03-30 09:02:14 +00:00
|
|
|
use rustc_middle::ty::adjustment::Adjust;
|
2023-06-16 16:02:11 +00:00
|
|
|
use rustc_middle::ty::{self, Ty, TyCtxt};
|
2020-01-11 11:37:08 +00:00
|
|
|
use rustc_session::{declare_lint_pass, declare_tool_lint};
|
2022-10-27 14:32:17 +00:00
|
|
|
use rustc_span::{sym, InnerSpan, Span};
|
2023-06-16 16:02:11 +00:00
|
|
|
use rustc_target::abi::VariantIdx;
|
|
|
|
use rustc_middle::mir::interpret::EvalToValTreeResult;
|
|
|
|
use rustc_middle::mir::interpret::GlobalId;
|
2018-06-06 15:20:22 +00:00
|
|
|
|
2020-10-09 10:45:29 +00:00
|
|
|
// FIXME: this is a correctness problem but there's no suitable
|
|
|
|
// warn-by-default category.
|
2018-06-06 15:20:22 +00:00
|
|
|
declare_clippy_lint! {
|
2021-07-29 10:16:06 +00:00
|
|
|
/// ### What it does
|
|
|
|
/// Checks for declaration of `const` items which is interior
|
2019-01-31 01:15:29 +00:00
|
|
|
/// mutable (e.g., contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.).
|
2019-03-05 16:50:33 +00:00
|
|
|
///
|
2021-07-29 10:16:06 +00:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// Consts are copied everywhere they are referenced, i.e.,
|
2019-03-05 16:50:33 +00:00
|
|
|
/// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
|
|
|
|
/// or `AtomicXxxx` will be created, which defeats the whole purpose of using
|
|
|
|
/// these types in the first place.
|
|
|
|
///
|
|
|
|
/// The `const` should better be replaced by a `static` item if a global
|
|
|
|
/// variable is wanted, or replaced by a `const fn` if a constructor is wanted.
|
|
|
|
///
|
2021-07-29 10:16:06 +00:00
|
|
|
/// ### Known problems
|
|
|
|
/// A "non-constant" const item is a legacy way to supply an
|
2019-01-31 01:15:29 +00:00
|
|
|
/// initialized value to downstream `static` items (e.g., the
|
2019-03-05 16:50:33 +00:00
|
|
|
/// `std::sync::ONCE_INIT` constant). In this case the use of `const` is legit,
|
|
|
|
/// and this lint should be suppressed.
|
|
|
|
///
|
2020-11-23 12:51:04 +00:00
|
|
|
/// Even though the lint avoids triggering on a constant whose type has enums that have variants
|
|
|
|
/// with interior mutability, and its value uses non interior mutable variants (see
|
|
|
|
/// [#3962](https://github.com/rust-lang/rust-clippy/issues/3962) and
|
|
|
|
/// [#3825](https://github.com/rust-lang/rust-clippy/issues/3825) for examples);
|
|
|
|
/// it complains about associated constants without default values only based on its types;
|
|
|
|
/// which might not be preferable.
|
|
|
|
/// There're other enums plus associated constants cases that the lint cannot handle.
|
2020-10-09 10:45:29 +00:00
|
|
|
///
|
|
|
|
/// Types that have underlying or potential interior mutability trigger the lint whether
|
|
|
|
/// the interior mutable field is used or not. See issues
|
|
|
|
/// [#5812](https://github.com/rust-lang/rust-clippy/issues/5812) and
|
|
|
|
///
|
2021-07-29 10:16:06 +00:00
|
|
|
/// ### Example
|
2019-03-05 16:50:33 +00:00
|
|
|
/// ```rust
|
|
|
|
/// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
|
|
|
|
///
|
|
|
|
/// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
|
|
|
|
/// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
|
|
|
|
/// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
|
2022-06-16 15:39:06 +00:00
|
|
|
/// ```
|
2019-03-05 16:50:33 +00:00
|
|
|
///
|
2022-06-16 15:39:06 +00:00
|
|
|
/// Use instead:
|
|
|
|
/// ```rust
|
|
|
|
/// # use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
|
2019-03-05 16:50:33 +00:00
|
|
|
/// static STATIC_ATOM: AtomicUsize = AtomicUsize::new(15);
|
|
|
|
/// STATIC_ATOM.store(9, SeqCst);
|
|
|
|
/// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
|
|
|
|
/// ```
|
2021-12-06 11:33:31 +00:00
|
|
|
#[clippy::version = "pre 1.29.0"]
|
2018-06-06 15:20:22 +00:00
|
|
|
pub DECLARE_INTERIOR_MUTABLE_CONST,
|
2020-10-09 10:45:29 +00:00
|
|
|
style,
|
2020-01-06 06:30:43 +00:00
|
|
|
"declaring `const` with interior mutability"
|
2018-06-06 15:20:22 +00:00
|
|
|
}
|
|
|
|
|
2020-10-09 10:45:29 +00:00
|
|
|
// FIXME: this is a correctness problem but there's no suitable
|
|
|
|
// warn-by-default category.
|
2018-06-06 15:20:22 +00:00
|
|
|
declare_clippy_lint! {
|
2021-07-29 10:16:06 +00:00
|
|
|
/// ### What it does
|
|
|
|
/// Checks if `const` items which is interior mutable (e.g.,
|
2019-01-31 01:15:29 +00:00
|
|
|
/// contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.) has been borrowed directly.
|
2019-03-05 16:50:33 +00:00
|
|
|
///
|
2021-07-29 10:16:06 +00:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// Consts are copied everywhere they are referenced, i.e.,
|
2019-03-05 16:50:33 +00:00
|
|
|
/// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
|
|
|
|
/// or `AtomicXxxx` will be created, which defeats the whole purpose of using
|
|
|
|
/// these types in the first place.
|
|
|
|
///
|
|
|
|
/// The `const` value should be stored inside a `static` item.
|
|
|
|
///
|
2021-07-29 10:16:06 +00:00
|
|
|
/// ### Known problems
|
|
|
|
/// When an enum has variants with interior mutability, use of its non
|
2020-10-09 10:45:29 +00:00
|
|
|
/// interior mutable variants can generate false positives. See issue
|
|
|
|
/// [#3962](https://github.com/rust-lang/rust-clippy/issues/3962)
|
|
|
|
///
|
|
|
|
/// Types that have underlying or potential interior mutability trigger the lint whether
|
|
|
|
/// the interior mutable field is used or not. See issues
|
|
|
|
/// [#5812](https://github.com/rust-lang/rust-clippy/issues/5812) and
|
|
|
|
/// [#3825](https://github.com/rust-lang/rust-clippy/issues/3825)
|
2019-03-05 16:50:33 +00:00
|
|
|
///
|
2021-07-29 10:16:06 +00:00
|
|
|
/// ### Example
|
2019-03-05 16:50:33 +00:00
|
|
|
/// ```rust
|
|
|
|
/// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
|
|
|
|
/// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
|
|
|
|
///
|
|
|
|
/// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
|
|
|
|
/// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
|
2022-06-16 15:39:06 +00:00
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// Use instead:
|
|
|
|
/// ```rust
|
|
|
|
/// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
|
|
|
|
/// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
|
2019-03-05 16:50:33 +00:00
|
|
|
///
|
|
|
|
/// static STATIC_ATOM: AtomicUsize = CONST_ATOM;
|
|
|
|
/// STATIC_ATOM.store(9, SeqCst);
|
|
|
|
/// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
|
|
|
|
/// ```
|
2021-12-06 11:33:31 +00:00
|
|
|
#[clippy::version = "pre 1.29.0"]
|
2018-06-06 15:20:22 +00:00
|
|
|
pub BORROW_INTERIOR_MUTABLE_CONST,
|
2020-10-09 10:45:29 +00:00
|
|
|
style,
|
2020-01-06 06:30:43 +00:00
|
|
|
"referencing `const` with interior mutability"
|
2018-06-06 15:20:22 +00:00
|
|
|
}
|
|
|
|
|
2020-11-23 12:51:04 +00:00
|
|
|
fn is_unfrozen<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
|
|
|
|
// Ignore types whose layout is unknown since `is_freeze` reports every generic types as `!Freeze`,
|
|
|
|
// making it indistinguishable from `UnsafeCell`. i.e. it isn't a tool to prove a type is
|
|
|
|
// 'unfrozen'. However, this code causes a false negative in which
|
2021-08-22 15:27:18 +00:00
|
|
|
// a type contains a layout-unknown type, but also an unsafe cell like `const CELL: Cell<T>`.
|
2020-11-23 12:51:04 +00:00
|
|
|
// Yet, it's better than `ty.has_type_flags(TypeFlags::HAS_TY_PARAM | TypeFlags::HAS_PROJECTION)`
|
|
|
|
// since it works when a pointer indirection involves (`Cell<*const T>`).
|
|
|
|
// Making up a `ParamEnv` where every generic params and assoc types are `Freeze`is another option;
|
|
|
|
// but I'm not sure whether it's a decent way, if possible.
|
2022-10-27 14:32:17 +00:00
|
|
|
cx.tcx.layout_of(cx.param_env.and(ty)).is_ok() && !ty.is_freeze(cx.tcx, cx.param_env)
|
2020-11-23 12:51:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn is_value_unfrozen_raw<'tcx>(
|
|
|
|
cx: &LateContext<'tcx>,
|
2023-06-16 16:02:11 +00:00
|
|
|
result: Result<Option<ty::ValTree<'tcx>>, ErrorHandled>,
|
2020-11-23 12:51:04 +00:00
|
|
|
ty: Ty<'tcx>,
|
|
|
|
) -> bool {
|
2023-06-16 16:02:11 +00:00
|
|
|
fn inner<'tcx>(cx: &LateContext<'tcx>, val: ty::ValTree<'tcx>, ty: Ty<'tcx>) -> bool {
|
|
|
|
match *ty.kind() {
|
2020-11-23 12:51:04 +00:00
|
|
|
// the fact that we have to dig into every structs to search enums
|
|
|
|
// leads us to the point checking `UnsafeCell` directly is the only option.
|
2022-07-07 10:46:22 +00:00
|
|
|
ty::Adt(ty_def, ..) if ty_def.is_unsafe_cell() => true,
|
2022-10-06 07:44:38 +00:00
|
|
|
// As of 2022-09-08 miri doesn't track which union field is active so there's no safe way to check the
|
|
|
|
// contained value.
|
|
|
|
ty::Adt(def, ..) if def.is_union() => false,
|
2023-06-16 16:02:11 +00:00
|
|
|
ty::Array(ty, _) => {
|
|
|
|
val.unwrap_branch().iter().any(|field| inner(cx, *field, ty))
|
2020-11-23 12:51:04 +00:00
|
|
|
},
|
2023-06-16 16:02:11 +00:00
|
|
|
ty::Adt(def, _) if def.is_union() => false,
|
2023-07-11 21:35:29 +00:00
|
|
|
ty::Adt(def, args) if def.is_enum() => {
|
2023-06-16 16:02:11 +00:00
|
|
|
let (&variant_index, fields) = val.unwrap_branch().split_first().unwrap();
|
|
|
|
let variant_index =
|
|
|
|
VariantIdx::from_u32(variant_index.unwrap_leaf().try_to_u32().ok().unwrap());
|
|
|
|
fields.iter().copied().zip(
|
|
|
|
def.variants()[variant_index]
|
|
|
|
.fields
|
|
|
|
.iter()
|
2023-07-11 21:35:29 +00:00
|
|
|
.map(|field| field.ty(cx.tcx, args))).any(|(field, ty)| inner(cx, field, ty))
|
2023-06-16 16:02:11 +00:00
|
|
|
}
|
2023-07-11 21:35:29 +00:00
|
|
|
ty::Adt(def, args) => {
|
|
|
|
val.unwrap_branch().iter().zip(def.non_enum_variant().fields.iter().map(|field| field.ty(cx.tcx, args))).any(|(field, ty)| inner(cx, *field, ty))
|
2023-06-16 16:02:11 +00:00
|
|
|
}
|
|
|
|
ty::Tuple(tys) => val.unwrap_branch().iter().zip(tys).any(|(field, ty)| inner(cx, *field, ty)),
|
2020-11-23 12:51:04 +00:00
|
|
|
_ => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
result.map_or_else(
|
|
|
|
|err| {
|
|
|
|
// Consider `TooGeneric` cases as being unfrozen.
|
|
|
|
// This causes a false positive where an assoc const whose type is unfrozen
|
|
|
|
// have a value that is a frozen variant with a generic param (an example is
|
|
|
|
// `declare_interior_mutable_const::enums::BothOfCellAndGeneric::GENERIC_VARIANT`).
|
|
|
|
// However, it prevents a number of false negatives that is, I think, important:
|
2023-07-02 12:35:19 +00:00
|
|
|
// 1. assoc consts in trait defs referring to consts of themselves (an example is
|
|
|
|
// `declare_interior_mutable_const::traits::ConcreteTypes::ANOTHER_ATOMIC`).
|
|
|
|
// 2. a path expr referring to assoc consts whose type is doesn't have any frozen variants in trait
|
|
|
|
// defs (i.e. without substitute for `Self`). (e.g. borrowing
|
|
|
|
// `borrow_interior_mutable_const::trait::ConcreteTypes::ATOMIC`)
|
|
|
|
// 3. similar to the false positive above; but the value is an unfrozen variant, or the type has no
|
|
|
|
// enums. (An example is
|
|
|
|
// `declare_interior_mutable_const::enums::BothOfCellAndGeneric::UNFROZEN_VARIANT` and
|
|
|
|
// `declare_interior_mutable_const::enums::BothOfCellAndGeneric::NO_ENUM`).
|
2020-11-23 12:51:04 +00:00
|
|
|
// One might be able to prevent these FNs correctly, and replace this with `false`;
|
|
|
|
// e.g. implementing `has_frozen_variant` described above, and not running this function
|
|
|
|
// when the type doesn't have any frozen variants would be the 'correct' way for the 2nd
|
|
|
|
// case (that actually removes another suboptimal behavior (I won't say 'false positive') where,
|
|
|
|
// similar to 2., but with the a frozen variant) (e.g. borrowing
|
|
|
|
// `borrow_interior_mutable_const::enums::AssocConsts::TO_BE_FROZEN_VARIANT`).
|
|
|
|
// I chose this way because unfrozen enums as assoc consts are rare (or, hopefully, none).
|
|
|
|
err == ErrorHandled::TooGeneric
|
|
|
|
},
|
2023-06-16 16:02:11 +00:00
|
|
|
|val| val.map_or(true, |val| inner(cx, val, ty)),
|
2020-11-23 12:51:04 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn is_value_unfrozen_poly<'tcx>(cx: &LateContext<'tcx>, body_id: BodyId, ty: Ty<'tcx>) -> bool {
|
2023-06-16 16:02:11 +00:00
|
|
|
let def_id = body_id.hir_id.owner.to_def_id();
|
2023-07-11 21:35:29 +00:00
|
|
|
let args = ty::GenericArgs::identity_for_item(cx.tcx, def_id);
|
|
|
|
let instance = ty::Instance::new(def_id, args);
|
2023-06-16 16:02:11 +00:00
|
|
|
let cid = rustc_middle::mir::interpret::GlobalId { instance, promoted: None };
|
|
|
|
let param_env = cx.tcx.param_env(def_id).with_reveal_all_normalized(cx.tcx);
|
|
|
|
let result = cx.tcx.const_eval_global_id_for_typeck(param_env, cid, None);
|
2020-11-23 12:51:04 +00:00
|
|
|
is_value_unfrozen_raw(cx, result, ty)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn is_value_unfrozen_expr<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId, def_id: DefId, ty: Ty<'tcx>) -> bool {
|
2023-07-11 21:35:29 +00:00
|
|
|
let args = cx.typeck_results().node_args(hir_id);
|
2020-11-23 12:51:04 +00:00
|
|
|
|
2023-07-11 21:35:29 +00:00
|
|
|
let result = const_eval_resolve(cx.tcx, cx.param_env, ty::UnevaluatedConst::new(def_id, args), None);
|
2020-11-23 12:51:04 +00:00
|
|
|
is_value_unfrozen_raw(cx, result, ty)
|
|
|
|
}
|
|
|
|
|
2023-06-16 16:02:11 +00:00
|
|
|
|
|
|
|
pub fn const_eval_resolve<'tcx>(
|
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
param_env: ty::ParamEnv<'tcx>,
|
|
|
|
ct: ty::UnevaluatedConst<'tcx>,
|
|
|
|
span: Option<Span>,
|
|
|
|
) -> EvalToValTreeResult<'tcx> {
|
2023-07-11 21:35:29 +00:00
|
|
|
match ty::Instance::resolve(tcx, param_env, ct.def, ct.args) {
|
2023-06-16 16:02:11 +00:00
|
|
|
Ok(Some(instance)) => {
|
|
|
|
let cid = GlobalId { instance, promoted: None };
|
|
|
|
tcx.const_eval_global_id_for_typeck(param_env, cid, span)
|
|
|
|
}
|
|
|
|
Ok(None) => Err(ErrorHandled::TooGeneric),
|
|
|
|
Err(err) => Err(ErrorHandled::Reported(err.into())),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-06-06 15:20:22 +00:00
|
|
|
#[derive(Copy, Clone)]
|
|
|
|
enum Source {
|
2018-11-27 20:14:15 +00:00
|
|
|
Item { item: Span },
|
2020-09-24 12:49:22 +00:00
|
|
|
Assoc { item: Span },
|
2018-11-27 20:14:15 +00:00
|
|
|
Expr { expr: Span },
|
2018-06-06 15:20:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Source {
|
2019-09-18 06:37:41 +00:00
|
|
|
#[must_use]
|
2018-06-06 15:20:22 +00:00
|
|
|
fn lint(&self) -> (&'static Lint, &'static str, Span) {
|
|
|
|
match self {
|
2019-07-31 00:25:35 +00:00
|
|
|
Self::Item { item } | Self::Assoc { item, .. } => (
|
2018-06-06 15:20:22 +00:00
|
|
|
DECLARE_INTERIOR_MUTABLE_CONST,
|
2020-01-06 06:30:43 +00:00
|
|
|
"a `const` item should never be interior mutable",
|
2018-06-06 15:20:22 +00:00
|
|
|
*item,
|
|
|
|
),
|
2019-07-31 00:25:35 +00:00
|
|
|
Self::Expr { expr } => (
|
2018-06-06 15:20:22 +00:00
|
|
|
BORROW_INTERIOR_MUTABLE_CONST,
|
2020-01-06 06:30:43 +00:00
|
|
|
"a `const` item with interior mutability should not be borrowed",
|
2018-06-06 15:20:22 +00:00
|
|
|
*expr,
|
|
|
|
),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-23 12:51:04 +00:00
|
|
|
fn lint(cx: &LateContext<'_>, source: Source) {
|
2018-06-06 15:20:22 +00:00
|
|
|
let (lint, msg, span) = source.lint();
|
2020-04-17 06:08:00 +00:00
|
|
|
span_lint_and_then(cx, lint, span, msg, |diag| {
|
2019-08-19 16:30:32 +00:00
|
|
|
if span.from_expansion() {
|
2018-06-06 15:20:22 +00:00
|
|
|
return; // Don't give suggestions into macros.
|
|
|
|
}
|
|
|
|
match source {
|
|
|
|
Source::Item { .. } => {
|
2019-06-12 08:28:58 +00:00
|
|
|
let const_kw_span = span.from_inner(InnerSpan::new(0, 5));
|
2020-04-17 06:08:00 +00:00
|
|
|
diag.span_label(const_kw_span, "make this a static item (maybe with lazy_static)");
|
2018-11-27 20:14:15 +00:00
|
|
|
},
|
2020-09-24 12:49:22 +00:00
|
|
|
Source::Assoc { .. } => (),
|
2018-06-06 15:20:22 +00:00
|
|
|
Source::Expr { .. } => {
|
2020-04-17 06:08:00 +00:00
|
|
|
diag.help("assign this const to a local or static variable, and use the variable here");
|
2018-11-27 20:14:15 +00:00
|
|
|
},
|
2018-06-06 15:20:22 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-04-08 20:43:55 +00:00
|
|
|
declare_lint_pass!(NonCopyConst => [DECLARE_INTERIOR_MUTABLE_CONST, BORROW_INTERIOR_MUTABLE_CONST]);
|
2018-06-06 15:20:22 +00:00
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
impl<'tcx> LateLintPass<'tcx> for NonCopyConst {
|
|
|
|
fn check_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx Item<'_>) {
|
2020-11-23 12:51:04 +00:00
|
|
|
if let ItemKind::Const(hir_ty, body_id) = it.kind {
|
2018-06-06 15:20:22 +00:00
|
|
|
let ty = hir_ty_to_ty(cx.tcx, hir_ty);
|
2022-07-28 17:08:22 +00:00
|
|
|
if !ignored_macro(cx, it) && is_unfrozen(cx, ty) && is_value_unfrozen_poly(cx, body_id, ty) {
|
2020-11-23 12:51:04 +00:00
|
|
|
lint(cx, Source::Item { item: it.span });
|
|
|
|
}
|
2018-06-06 15:20:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
fn check_trait_item(&mut self, cx: &LateContext<'tcx>, trait_item: &'tcx TraitItem<'_>) {
|
2020-11-23 12:51:04 +00:00
|
|
|
if let TraitItemKind::Const(hir_ty, body_id_opt) = &trait_item.kind {
|
2018-06-06 15:20:22 +00:00
|
|
|
let ty = hir_ty_to_ty(cx.tcx, hir_ty);
|
2020-11-23 12:51:04 +00:00
|
|
|
|
2020-09-24 12:49:22 +00:00
|
|
|
// Normalize assoc types because ones originated from generic params
|
|
|
|
// bounded other traits could have their bound.
|
|
|
|
let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
|
2020-11-23 12:51:04 +00:00
|
|
|
if is_unfrozen(cx, normalized)
|
|
|
|
// When there's no default value, lint it only according to its type;
|
|
|
|
// in other words, lint consts whose value *could* be unfrozen, not definitely is.
|
|
|
|
// This feels inconsistent with how the lint treats generic types,
|
|
|
|
// which avoids linting types which potentially become unfrozen.
|
2021-08-22 15:27:18 +00:00
|
|
|
// One could check whether an unfrozen type have a *frozen variant*
|
2020-11-23 12:51:04 +00:00
|
|
|
// (like `body_id_opt.map_or_else(|| !has_frozen_variant(...), ...)`),
|
|
|
|
// and do the same as the case of generic types at impl items.
|
|
|
|
// Note that it isn't sufficient to check if it has an enum
|
|
|
|
// since all of that enum's variants can be unfrozen:
|
|
|
|
// i.e. having an enum doesn't necessary mean a type has a frozen variant.
|
|
|
|
// And, implementing it isn't a trivial task; it'll probably end up
|
|
|
|
// re-implementing the trait predicate evaluation specific to `Freeze`.
|
|
|
|
&& body_id_opt.map_or(true, |body_id| is_value_unfrozen_poly(cx, body_id, normalized))
|
|
|
|
{
|
|
|
|
lint(cx, Source::Assoc { item: trait_item.span });
|
|
|
|
}
|
2018-06-06 15:20:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx ImplItem<'_>) {
|
2020-11-23 12:51:04 +00:00
|
|
|
if let ImplItemKind::Const(hir_ty, body_id) = &impl_item.kind {
|
2022-09-20 05:11:23 +00:00
|
|
|
let item_def_id = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id;
|
2021-10-20 20:38:10 +00:00
|
|
|
let item = cx.tcx.hir().expect_item(item_def_id);
|
2020-09-24 12:49:22 +00:00
|
|
|
|
|
|
|
match &item.kind {
|
2020-11-22 22:46:21 +00:00
|
|
|
ItemKind::Impl(Impl {
|
2020-09-24 12:49:22 +00:00
|
|
|
of_trait: Some(of_trait_ref),
|
|
|
|
..
|
2020-11-22 22:46:21 +00:00
|
|
|
}) => {
|
2020-09-24 12:49:22 +00:00
|
|
|
if_chain! {
|
|
|
|
// Lint a trait impl item only when the definition is a generic type,
|
2021-08-22 12:46:15 +00:00
|
|
|
// assuming an assoc const is not meant to be an interior mutable type.
|
2020-09-24 12:49:22 +00:00
|
|
|
if let Some(of_trait_def_id) = of_trait_ref.trait_def_id();
|
2021-11-18 22:33:49 +00:00
|
|
|
if let Some(of_assoc_item) = cx
|
|
|
|
.tcx
|
2022-10-27 03:02:18 +00:00
|
|
|
.associated_item(impl_item.owner_id)
|
2021-11-18 22:33:49 +00:00
|
|
|
.trait_item_def_id;
|
2020-09-24 12:49:22 +00:00
|
|
|
if cx
|
|
|
|
.tcx
|
|
|
|
.layout_of(cx.tcx.param_env(of_trait_def_id).and(
|
|
|
|
// Normalize assoc types because ones originated from generic params
|
|
|
|
// bounded other traits could have their bound at the trait defs;
|
|
|
|
// and, in that case, the definition is *not* generic.
|
|
|
|
cx.tcx.normalize_erasing_regions(
|
|
|
|
cx.tcx.param_env(of_trait_def_id),
|
2023-07-11 21:35:29 +00:00
|
|
|
cx.tcx.type_of(of_assoc_item).instantiate_identity(),
|
2020-09-24 12:49:22 +00:00
|
|
|
),
|
|
|
|
))
|
|
|
|
.is_err();
|
2020-11-23 12:51:04 +00:00
|
|
|
// If there were a function like `has_frozen_variant` described above,
|
|
|
|
// we should use here as a frozen variant is a potential to be frozen
|
|
|
|
// similar to unknown layouts.
|
|
|
|
// e.g. `layout_of(...).is_err() || has_frozen_variant(...);`
|
2021-04-08 15:50:13 +00:00
|
|
|
let ty = hir_ty_to_ty(cx.tcx, hir_ty);
|
|
|
|
let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
|
|
|
|
if is_unfrozen(cx, normalized);
|
|
|
|
if is_value_unfrozen_poly(cx, *body_id, normalized);
|
2020-09-24 12:49:22 +00:00
|
|
|
then {
|
2021-04-08 15:50:13 +00:00
|
|
|
lint(
|
|
|
|
cx,
|
|
|
|
Source::Assoc {
|
|
|
|
item: impl_item.span,
|
|
|
|
},
|
|
|
|
);
|
2020-09-24 12:49:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
2020-11-22 22:46:21 +00:00
|
|
|
ItemKind::Impl(Impl { of_trait: None, .. }) => {
|
2020-09-24 12:49:22 +00:00
|
|
|
let ty = hir_ty_to_ty(cx.tcx, hir_ty);
|
|
|
|
// Normalize assoc types originated from generic params.
|
|
|
|
let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
|
2020-11-23 12:51:04 +00:00
|
|
|
|
|
|
|
if is_unfrozen(cx, ty) && is_value_unfrozen_poly(cx, *body_id, normalized) {
|
|
|
|
lint(cx, Source::Assoc { item: impl_item.span });
|
|
|
|
}
|
2020-09-24 12:49:22 +00:00
|
|
|
},
|
|
|
|
_ => (),
|
2018-06-06 15:20:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
|
2019-09-27 15:16:06 +00:00
|
|
|
if let ExprKind::Path(qpath) = &expr.kind {
|
2018-06-06 15:20:22 +00:00
|
|
|
// Only lint if we use the const item inside a function.
|
2019-02-24 18:43:15 +00:00
|
|
|
if in_constant(cx, expr.hir_id) {
|
2018-06-06 15:20:22 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-01-31 01:15:29 +00:00
|
|
|
// Make sure it is a const item.
|
2022-10-23 13:18:45 +00:00
|
|
|
let Res::Def(DefKind::Const | DefKind::AssocConst, item_def_id) = cx.qpath_res(qpath, expr.hir_id) else {
|
|
|
|
return
|
2018-06-06 15:20:22 +00:00
|
|
|
};
|
|
|
|
|
2019-01-31 01:15:29 +00:00
|
|
|
// Climb up to resolve any field access and explicit referencing.
|
2018-06-06 15:20:22 +00:00
|
|
|
let mut cur_expr = expr;
|
|
|
|
let mut dereferenced_expr = expr;
|
|
|
|
let mut needs_check_adjustment = true;
|
|
|
|
loop {
|
2023-01-03 07:31:04 +00:00
|
|
|
let parent_id = cx.tcx.hir().parent_id(cur_expr.hir_id);
|
2019-02-24 18:43:15 +00:00
|
|
|
if parent_id == cur_expr.hir_id {
|
2018-06-06 15:20:22 +00:00
|
|
|
break;
|
|
|
|
}
|
2019-06-25 21:34:07 +00:00
|
|
|
if let Some(Node::Expr(parent_expr)) = cx.tcx.hir().find(parent_id) {
|
2019-09-27 15:16:06 +00:00
|
|
|
match &parent_expr.kind {
|
2018-07-12 07:30:57 +00:00
|
|
|
ExprKind::AddrOf(..) => {
|
2019-01-31 01:15:29 +00:00
|
|
|
// `&e` => `e` must be referenced.
|
2018-06-06 15:20:22 +00:00
|
|
|
needs_check_adjustment = false;
|
2018-11-27 20:14:15 +00:00
|
|
|
},
|
2018-07-12 07:30:57 +00:00
|
|
|
ExprKind::Field(..) => {
|
2018-06-06 15:20:22 +00:00
|
|
|
needs_check_adjustment = true;
|
2020-08-28 14:10:16 +00:00
|
|
|
|
|
|
|
// Check whether implicit dereferences happened;
|
|
|
|
// if so, no need to go further up
|
|
|
|
// because of the same reason as the `ExprKind::Unary` case.
|
|
|
|
if cx
|
|
|
|
.typeck_results()
|
|
|
|
.expr_adjustments(dereferenced_expr)
|
|
|
|
.iter()
|
|
|
|
.any(|adj| matches!(adj.kind, Adjust::Deref(_)))
|
|
|
|
{
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
dereferenced_expr = parent_expr;
|
2018-11-27 20:14:15 +00:00
|
|
|
},
|
2018-07-12 07:30:57 +00:00
|
|
|
ExprKind::Index(e, _) if ptr::eq(&**e, cur_expr) => {
|
2018-06-06 15:20:22 +00:00
|
|
|
// `e[i]` => desugared to `*Index::index(&e, i)`,
|
|
|
|
// meaning `e` must be referenced.
|
|
|
|
// no need to go further up since a method call is involved now.
|
|
|
|
needs_check_adjustment = false;
|
|
|
|
break;
|
2018-11-27 20:14:15 +00:00
|
|
|
},
|
2021-02-09 08:15:53 +00:00
|
|
|
ExprKind::Unary(UnOp::Deref, _) => {
|
2018-06-06 15:20:22 +00:00
|
|
|
// `*e` => desugared to `*Deref::deref(&e)`,
|
|
|
|
// meaning `e` must be referenced.
|
|
|
|
// no need to go further up since a method call is involved now.
|
|
|
|
needs_check_adjustment = false;
|
|
|
|
break;
|
2018-11-27 20:14:15 +00:00
|
|
|
},
|
2018-06-06 15:20:22 +00:00
|
|
|
_ => break,
|
|
|
|
}
|
|
|
|
cur_expr = parent_expr;
|
|
|
|
} else {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-11 21:07:04 +00:00
|
|
|
let ty = if needs_check_adjustment {
|
2020-07-17 08:47:04 +00:00
|
|
|
let adjustments = cx.typeck_results().expr_adjustments(dereferenced_expr);
|
2020-07-14 12:59:59 +00:00
|
|
|
if let Some(i) = adjustments
|
|
|
|
.iter()
|
|
|
|
.position(|adj| matches!(adj.kind, Adjust::Borrow(_) | Adjust::Deref(_)))
|
|
|
|
{
|
2018-06-06 15:20:22 +00:00
|
|
|
if i == 0 {
|
2020-07-17 08:47:04 +00:00
|
|
|
cx.typeck_results().expr_ty(dereferenced_expr)
|
2018-06-06 15:20:22 +00:00
|
|
|
} else {
|
|
|
|
adjustments[i - 1].target
|
|
|
|
}
|
|
|
|
} else {
|
2019-01-31 01:15:29 +00:00
|
|
|
// No borrow adjustments means the entire const is moved.
|
2018-06-06 15:20:22 +00:00
|
|
|
return;
|
|
|
|
}
|
2018-08-11 21:07:04 +00:00
|
|
|
} else {
|
2020-07-17 08:47:04 +00:00
|
|
|
cx.typeck_results().expr_ty(dereferenced_expr)
|
2018-06-06 15:20:22 +00:00
|
|
|
};
|
|
|
|
|
2020-11-23 12:51:04 +00:00
|
|
|
if is_unfrozen(cx, ty) && is_value_unfrozen_expr(cx, expr.hir_id, item_def_id, ty) {
|
|
|
|
lint(cx, Source::Expr { expr: expr.span });
|
|
|
|
}
|
2018-06-06 15:20:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-07-28 17:08:22 +00:00
|
|
|
|
|
|
|
fn ignored_macro(cx: &LateContext<'_>, it: &rustc_hir::Item<'_>) -> bool {
|
|
|
|
macro_backtrace(it.span).any(|macro_call| {
|
|
|
|
matches!(
|
|
|
|
cx.tcx.get_diagnostic_name(macro_call.def_id),
|
|
|
|
Some(sym::thread_local_macro)
|
|
|
|
)
|
|
|
|
})
|
|
|
|
}
|