1 //! Checks for uses of const which the type is not `Freeze` (`Cell`-free).
3 //! This lint is **warn** 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::{AssocKind, Ty};
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 use rustc_span::{InnerSpan, Span, DUMMY_SP};
15 use rustc_typeck::hir_ty_to_ty;
17 use crate::utils::{in_constant, qpath_res, span_lint_and_then};
18 use if_chain::if_chain;
20 // FIXME: this is a correctness problem but there's no suitable
21 // warn-by-default category.
22 declare_clippy_lint! {
23 /// **What it does:** Checks for declaration of `const` items which is interior
24 /// mutable (e.g., contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.).
26 /// **Why is this bad?** Consts are copied everywhere they are referenced, i.e.,
27 /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
28 /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
29 /// these types in the first place.
31 /// The `const` should better be replaced by a `static` item if a global
32 /// variable is wanted, or replaced by a `const fn` if a constructor is wanted.
34 /// **Known problems:** A "non-constant" const item is a legacy way to supply an
35 /// initialized value to downstream `static` items (e.g., the
36 /// `std::sync::ONCE_INIT` constant). In this case the use of `const` is legit,
37 /// and this lint should be suppressed.
39 /// When an enum has variants with interior mutability, use of its non interior mutable
40 /// variants can generate false positives. See issue
41 /// [#3962](https://github.com/rust-lang/rust-clippy/issues/3962)
43 /// Types that have underlying or potential interior mutability trigger the lint whether
44 /// the interior mutable field is used or not. See issues
45 /// [#5812](https://github.com/rust-lang/rust-clippy/issues/5812) and
46 /// [#3825](https://github.com/rust-lang/rust-clippy/issues/3825)
50 /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
53 /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
54 /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
55 /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
58 /// static STATIC_ATOM: AtomicUsize = AtomicUsize::new(15);
59 /// STATIC_ATOM.store(9, SeqCst);
60 /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
62 pub DECLARE_INTERIOR_MUTABLE_CONST,
64 "declaring `const` with interior mutability"
67 // FIXME: this is a correctness problem but there's no suitable
68 // warn-by-default category.
69 declare_clippy_lint! {
70 /// **What it does:** Checks if `const` items which is interior mutable (e.g.,
71 /// contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.) has been borrowed directly.
73 /// **Why is this bad?** Consts are copied everywhere they are referenced, i.e.,
74 /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
75 /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
76 /// these types in the first place.
78 /// The `const` value should be stored inside a `static` item.
80 /// **Known problems:** When an enum has variants with interior mutability, use of its non
81 /// interior mutable variants can generate false positives. See issue
82 /// [#3962](https://github.com/rust-lang/rust-clippy/issues/3962)
84 /// Types that have underlying or potential interior mutability trigger the lint whether
85 /// the interior mutable field is used or not. See issues
86 /// [#5812](https://github.com/rust-lang/rust-clippy/issues/5812) and
87 /// [#3825](https://github.com/rust-lang/rust-clippy/issues/3825)
91 /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
92 /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
95 /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
96 /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
99 /// static STATIC_ATOM: AtomicUsize = CONST_ATOM;
100 /// STATIC_ATOM.store(9, SeqCst);
101 /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
103 pub BORROW_INTERIOR_MUTABLE_CONST,
105 "referencing `const` with interior mutability"
108 #[derive(Copy, Clone)]
111 Assoc { item: Span },
117 fn lint(&self) -> (&'static Lint, &'static str, Span) {
119 Self::Item { item } | Self::Assoc { item, .. } => (
120 DECLARE_INTERIOR_MUTABLE_CONST,
121 "a `const` item should never be interior mutable",
124 Self::Expr { expr } => (
125 BORROW_INTERIOR_MUTABLE_CONST,
126 "a `const` item with interior mutability should not be borrowed",
133 fn verify_ty_bound<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, source: Source) {
134 // Ignore types whose layout is unknown since `is_freeze` reports every generic types as `!Freeze`,
135 // making it indistinguishable from `UnsafeCell`. i.e. it isn't a tool to prove a type is
136 // 'unfrozen'. However, this code causes a false negative in which
137 // a type contains a layout-unknown type, but also a unsafe cell like `const CELL: Cell<T>`.
138 // Yet, it's better than `ty.has_type_flags(TypeFlags::HAS_TY_PARAM | TypeFlags::HAS_PROJECTION)`
139 // since it works when a pointer indirection involves (`Cell<*const T>`).
140 // Making up a `ParamEnv` where every generic params and assoc types are `Freeze`is another option;
141 // but I'm not sure whether it's a decent way, if possible.
142 if cx.tcx.layout_of(cx.param_env.and(ty)).is_err() || ty.is_freeze(cx.tcx.at(DUMMY_SP), cx.param_env) {
146 let (lint, msg, span) = source.lint();
147 span_lint_and_then(cx, lint, span, msg, |diag| {
148 if span.from_expansion() {
149 return; // Don't give suggestions into macros.
152 Source::Item { .. } => {
153 let const_kw_span = span.from_inner(InnerSpan::new(0, 5));
154 diag.span_label(const_kw_span, "make this a static item (maybe with lazy_static)");
156 Source::Assoc { .. } => (),
157 Source::Expr { .. } => {
158 diag.help("assign this const to a local or static variable, and use the variable here");
164 declare_lint_pass!(NonCopyConst => [DECLARE_INTERIOR_MUTABLE_CONST, BORROW_INTERIOR_MUTABLE_CONST]);
166 impl<'tcx> LateLintPass<'tcx> for NonCopyConst {
167 fn check_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx Item<'_>) {
168 if let ItemKind::Const(hir_ty, ..) = &it.kind {
169 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
170 verify_ty_bound(cx, ty, Source::Item { item: it.span });
174 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, trait_item: &'tcx TraitItem<'_>) {
175 if let TraitItemKind::Const(hir_ty, ..) = &trait_item.kind {
176 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
177 // Normalize assoc types because ones originated from generic params
178 // bounded other traits could have their bound.
179 let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
180 verify_ty_bound(cx, normalized, Source::Assoc { item: trait_item.span });
184 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx ImplItem<'_>) {
185 if let ImplItemKind::Const(hir_ty, ..) = &impl_item.kind {
186 let item_hir_id = cx.tcx.hir().get_parent_node(impl_item.hir_id);
187 let item = cx.tcx.hir().expect_item(item_hir_id);
191 of_trait: Some(of_trait_ref),
195 // Lint a trait impl item only when the definition is a generic type,
196 // assuming a assoc const is not meant to be a interior mutable type.
197 if let Some(of_trait_def_id) = of_trait_ref.trait_def_id();
198 if let Some(of_assoc_item) = specialization_graph::Node::Trait(of_trait_def_id)
199 .item(cx.tcx, impl_item.ident, AssocKind::Const, of_trait_def_id);
202 .layout_of(cx.tcx.param_env(of_trait_def_id).and(
203 // Normalize assoc types because ones originated from generic params
204 // bounded other traits could have their bound at the trait defs;
205 // and, in that case, the definition is *not* generic.
206 cx.tcx.normalize_erasing_regions(
207 cx.tcx.param_env(of_trait_def_id),
208 cx.tcx.type_of(of_assoc_item.def_id),
213 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
214 let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
219 item: impl_item.span,
225 ItemKind::Impl { of_trait: None, .. } => {
226 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
227 // Normalize assoc types originated from generic params.
228 let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
229 verify_ty_bound(cx, normalized, Source::Assoc { item: impl_item.span });
236 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
237 if let ExprKind::Path(qpath) = &expr.kind {
238 // Only lint if we use the const item inside a function.
239 if in_constant(cx, expr.hir_id) {
243 // Make sure it is a const item.
244 match qpath_res(cx, qpath, expr.hir_id) {
245 Res::Def(DefKind::Const | DefKind::AssocConst, _) => {},
249 // Climb up to resolve any field access and explicit referencing.
250 let mut cur_expr = expr;
251 let mut dereferenced_expr = expr;
252 let mut needs_check_adjustment = true;
254 let parent_id = cx.tcx.hir().get_parent_node(cur_expr.hir_id);
255 if parent_id == cur_expr.hir_id {
258 if let Some(Node::Expr(parent_expr)) = cx.tcx.hir().find(parent_id) {
259 match &parent_expr.kind {
260 ExprKind::AddrOf(..) => {
261 // `&e` => `e` must be referenced.
262 needs_check_adjustment = false;
264 ExprKind::Field(..) => {
265 needs_check_adjustment = true;
267 // Check whether implicit dereferences happened;
268 // if so, no need to go further up
269 // because of the same reason as the `ExprKind::Unary` case.
272 .expr_adjustments(dereferenced_expr)
274 .any(|adj| matches!(adj.kind, Adjust::Deref(_)))
279 dereferenced_expr = parent_expr;
281 ExprKind::Index(e, _) if ptr::eq(&**e, cur_expr) => {
282 // `e[i]` => desugared to `*Index::index(&e, i)`,
283 // meaning `e` must be referenced.
284 // no need to go further up since a method call is involved now.
285 needs_check_adjustment = false;
288 ExprKind::Unary(UnOp::UnDeref, _) => {
289 // `*e` => desugared to `*Deref::deref(&e)`,
290 // meaning `e` must be referenced.
291 // no need to go further up since a method call is involved now.
292 needs_check_adjustment = false;
297 cur_expr = parent_expr;
303 let ty = if needs_check_adjustment {
304 let adjustments = cx.typeck_results().expr_adjustments(dereferenced_expr);
305 if let Some(i) = adjustments
307 .position(|adj| matches!(adj.kind, Adjust::Borrow(_) | Adjust::Deref(_)))
310 cx.typeck_results().expr_ty(dereferenced_expr)
312 adjustments[i - 1].target
315 // No borrow adjustments means the entire const is moved.
319 cx.typeck_results().expr_ty(dereferenced_expr)
322 verify_ty_bound(cx, ty, Source::Expr { expr: expr.span });