1 //! Checks for uses of const which the type is not `Freeze` (`Cell`-free).
3 //! This lint is **deny** by default.
7 use rustc_hir::def::{DefKind, Res};
8 use rustc_hir::{Expr, ExprKind, ImplItem, ImplItemKind, Item, ItemKind, Node, TraitItem, TraitItemKind, UnOp};
9 use rustc_infer::traits::specialization_graph;
10 use rustc_lint::{LateContext, LateLintPass, Lint};
11 use rustc_middle::ty::adjustment::Adjust;
12 use rustc_middle::ty::fold::TypeFoldable as _;
13 use rustc_middle::ty::{AssocKind, Ty, TypeFlags};
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
15 use rustc_span::{InnerSpan, Span, DUMMY_SP};
16 use rustc_typeck::hir_ty_to_ty;
18 use crate::utils::{in_constant, qpath_res, span_lint_and_then};
19 use if_chain::if_chain;
21 declare_clippy_lint! {
22 /// **What it does:** Checks for declaration of `const` items which is interior
23 /// mutable (e.g., contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.).
25 /// **Why is this bad?** Consts are copied everywhere they are referenced, i.e.,
26 /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
27 /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
28 /// these types in the first place.
30 /// The `const` should better be replaced by a `static` item if a global
31 /// variable is wanted, or replaced by a `const fn` if a constructor is wanted.
33 /// **Known problems:** A "non-constant" const item is a legacy way to supply an
34 /// initialized value to downstream `static` items (e.g., the
35 /// `std::sync::ONCE_INIT` constant). In this case the use of `const` is legit,
36 /// and this lint should be suppressed.
40 /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
43 /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
44 /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
45 /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
48 /// static STATIC_ATOM: AtomicUsize = AtomicUsize::new(15);
49 /// STATIC_ATOM.store(9, SeqCst);
50 /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
52 pub DECLARE_INTERIOR_MUTABLE_CONST,
54 "declaring `const` with interior mutability"
57 declare_clippy_lint! {
58 /// **What it does:** Checks if `const` items which is interior mutable (e.g.,
59 /// contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.) has been borrowed directly.
61 /// **Why is this bad?** Consts are copied everywhere they are referenced, i.e.,
62 /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
63 /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
64 /// these types in the first place.
66 /// The `const` value should be stored inside a `static` item.
68 /// **Known problems:** None
72 /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
73 /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
76 /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
77 /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
80 /// static STATIC_ATOM: AtomicUsize = CONST_ATOM;
81 /// STATIC_ATOM.store(9, SeqCst);
82 /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
84 pub BORROW_INTERIOR_MUTABLE_CONST,
86 "referencing `const` with interior mutability"
89 #[derive(Copy, Clone)]
98 fn lint(&self) -> (&'static Lint, &'static str, Span) {
100 Self::Item { item } | Self::Assoc { item, .. } => (
101 DECLARE_INTERIOR_MUTABLE_CONST,
102 "a `const` item should never be interior mutable",
105 Self::Expr { expr } => (
106 BORROW_INTERIOR_MUTABLE_CONST,
107 "a `const` item with interior mutability should not be borrowed",
114 fn verify_ty_bound<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, source: Source) {
115 // Ignore types whose layout is unknown since `is_freeze` reports every generic types as `!Freeze`,
116 // making it indistinguishable from `UnsafeCell`. i.e. it isn't a tool to prove a type is
117 // 'unfrozen'. However, this code causes a false negative in which
118 // a type contains a layout-unknown type, but also a unsafe cell like `const CELL: Cell<T>`.
119 // Yet, it's better than `ty.has_type_flags(TypeFlags::HAS_TY_PARAM | TypeFlags::HAS_PROJECTION)`
120 // since it works when a pointer indirection involves (`Cell<*const T>`).
121 // Making up a `ParamEnv` where every generic params and assoc types are `Freeze`is another option;
122 // but I'm not sure whether it's a decent way, if possible.
123 if cx.tcx.layout_of(cx.param_env.and(ty)).is_err() || ty.is_freeze(cx.tcx.at(DUMMY_SP), cx.param_env) {
127 let (lint, msg, span) = source.lint();
128 span_lint_and_then(cx, lint, span, msg, |diag| {
129 if span.from_expansion() {
130 return; // Don't give suggestions into macros.
133 Source::Item { .. } => {
134 let const_kw_span = span.from_inner(InnerSpan::new(0, 5));
135 diag.span_label(const_kw_span, "make this a static item (maybe with lazy_static)");
137 Source::Assoc { .. } => (),
138 Source::Expr { .. } => {
139 diag.help("assign this const to a local or static variable, and use the variable here");
145 declare_lint_pass!(NonCopyConst => [DECLARE_INTERIOR_MUTABLE_CONST, BORROW_INTERIOR_MUTABLE_CONST]);
147 impl<'tcx> LateLintPass<'tcx> for NonCopyConst {
148 fn check_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx Item<'_>) {
149 if let ItemKind::Const(hir_ty, ..) = &it.kind {
150 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
151 verify_ty_bound(cx, ty, Source::Item { item: it.span });
155 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, trait_item: &'tcx TraitItem<'_>) {
156 if let TraitItemKind::Const(hir_ty, ..) = &trait_item.kind {
157 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
158 // Normalize assoc types because ones originated from generic params
159 // bounded other traits could have their bound.
160 let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
161 verify_ty_bound(cx, normalized, Source::Assoc { item: trait_item.span });
165 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx ImplItem<'_>) {
166 if let ImplItemKind::Const(hir_ty, ..) = &impl_item.kind {
167 let item_hir_id = cx.tcx.hir().get_parent_node(impl_item.hir_id);
168 let item = cx.tcx.hir().expect_item(item_hir_id);
172 of_trait: Some(of_trait_ref),
176 // Lint a trait impl item only when the definition is a generic type,
177 // assuming a assoc const is not meant to be a interior mutable type.
178 if let Some(of_trait_def_id) = of_trait_ref.trait_def_id();
179 if let Some(of_assoc_item) = specialization_graph::Node::Trait(of_trait_def_id)
180 .item(cx.tcx, impl_item.ident, AssocKind::Const, of_trait_def_id);
182 // Normalize assoc types because ones originated from generic params
183 // bounded other traits could have their bound at the trait defs;
184 // and, in that case, the definition is *not* generic.
185 .normalize_erasing_regions(
186 cx.tcx.param_env(of_trait_def_id),
187 cx.tcx.type_of(of_assoc_item.def_id),
189 .has_type_flags(TypeFlags::HAS_PROJECTION | TypeFlags::HAS_TY_PARAM);
191 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
192 let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
197 item: impl_item.span,
203 ItemKind::Impl { of_trait: None, .. } => {
204 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
205 // Normalize assoc types originated from generic params.
206 let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
207 verify_ty_bound(cx, normalized, Source::Assoc { item: impl_item.span });
214 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
215 if let ExprKind::Path(qpath) = &expr.kind {
216 // Only lint if we use the const item inside a function.
217 if in_constant(cx, expr.hir_id) {
221 // Make sure it is a const item.
222 match qpath_res(cx, qpath, expr.hir_id) {
223 Res::Def(DefKind::Const | DefKind::AssocConst, _) => {},
227 // Climb up to resolve any field access and explicit referencing.
228 let mut cur_expr = expr;
229 let mut dereferenced_expr = expr;
230 let mut needs_check_adjustment = true;
232 let parent_id = cx.tcx.hir().get_parent_node(cur_expr.hir_id);
233 if parent_id == cur_expr.hir_id {
236 if let Some(Node::Expr(parent_expr)) = cx.tcx.hir().find(parent_id) {
237 match &parent_expr.kind {
238 ExprKind::AddrOf(..) => {
239 // `&e` => `e` must be referenced.
240 needs_check_adjustment = false;
242 ExprKind::Field(..) => {
243 needs_check_adjustment = true;
245 // Check whether implicit dereferences happened;
246 // if so, no need to go further up
247 // because of the same reason as the `ExprKind::Unary` case.
250 .expr_adjustments(dereferenced_expr)
252 .any(|adj| matches!(adj.kind, Adjust::Deref(_)))
257 dereferenced_expr = parent_expr;
259 ExprKind::Index(e, _) if ptr::eq(&**e, cur_expr) => {
260 // `e[i]` => desugared to `*Index::index(&e, i)`,
261 // meaning `e` must be referenced.
262 // no need to go further up since a method call is involved now.
263 needs_check_adjustment = false;
266 ExprKind::Unary(UnOp::UnDeref, _) => {
267 // `*e` => desugared to `*Deref::deref(&e)`,
268 // meaning `e` must be referenced.
269 // no need to go further up since a method call is involved now.
270 needs_check_adjustment = false;
275 cur_expr = parent_expr;
281 let ty = if needs_check_adjustment {
282 let adjustments = cx.typeck_results().expr_adjustments(dereferenced_expr);
283 if let Some(i) = adjustments
285 .position(|adj| matches!(adj.kind, Adjust::Borrow(_) | Adjust::Deref(_)))
288 cx.typeck_results().expr_ty(dereferenced_expr)
290 adjustments[i - 1].target
293 // No borrow adjustments means the entire const is moved.
297 cx.typeck_results().expr_ty(dereferenced_expr)
300 verify_ty_bound(cx, ty, Source::Expr { expr: expr.span });