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::{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 declare_clippy_lint! {
21 /// **What it does:** Checks for declaration of `const` items which is interior
22 /// mutable (e.g., contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.).
24 /// **Why is this bad?** Consts are copied everywhere they are referenced, i.e.,
25 /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
26 /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
27 /// these types in the first place.
29 /// The `const` should better be replaced by a `static` item if a global
30 /// variable is wanted, or replaced by a `const fn` if a constructor is wanted.
32 /// **Known problems:** A "non-constant" const item is a legacy way to supply an
33 /// initialized value to downstream `static` items (e.g., the
34 /// `std::sync::ONCE_INIT` constant). In this case the use of `const` is legit,
35 /// and this lint should be suppressed.
39 /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
42 /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
43 /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
44 /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
47 /// static STATIC_ATOM: AtomicUsize = AtomicUsize::new(15);
48 /// STATIC_ATOM.store(9, SeqCst);
49 /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
51 pub DECLARE_INTERIOR_MUTABLE_CONST,
53 "declaring `const` with interior mutability"
56 declare_clippy_lint! {
57 /// **What it does:** Checks if `const` items which is interior mutable (e.g.,
58 /// contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.) has been borrowed directly.
60 /// **Why is this bad?** Consts are copied everywhere they are referenced, i.e.,
61 /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
62 /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
63 /// these types in the first place.
65 /// The `const` value should be stored inside a `static` item.
67 /// **Known problems:** None
71 /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
72 /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
75 /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
76 /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
79 /// static STATIC_ATOM: AtomicUsize = CONST_ATOM;
80 /// STATIC_ATOM.store(9, SeqCst);
81 /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
83 pub BORROW_INTERIOR_MUTABLE_CONST,
85 "referencing `const` with interior mutability"
88 #[derive(Copy, Clone)]
97 fn lint(&self) -> (&'static Lint, &'static str, Span) {
99 Self::Item { item } | Self::Assoc { item, .. } => (
100 DECLARE_INTERIOR_MUTABLE_CONST,
101 "a `const` item should never be interior mutable",
104 Self::Expr { expr } => (
105 BORROW_INTERIOR_MUTABLE_CONST,
106 "a `const` item with interior mutability should not be borrowed",
113 fn verify_ty_bound<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, source: Source) {
114 // Ignore types whose layout is unknown since `is_freeze` reports every generic types as `!Freeze`,
115 // making it indistinguishable from `UnsafeCell`. i.e. it isn't a tool to prove a type is
116 // 'unfrozen'. However, this code causes a false negative in which
117 // a type contains a layout-unknown type, but also a unsafe cell like `const CELL: Cell<T>`.
118 // Yet, it's better than `ty.has_type_flags(TypeFlags::HAS_TY_PARAM | TypeFlags::HAS_PROJECTION)`
119 // since it works when a pointer indirection involves (`Cell<*const T>`).
120 // Making up a `ParamEnv` where every generic params and assoc types are `Freeze`is another option;
121 // but I'm not sure whether it's a decent way, if possible.
122 if cx.tcx.layout_of(cx.param_env.and(ty)).is_err() || ty.is_freeze(cx.tcx.at(DUMMY_SP), cx.param_env) {
126 let (lint, msg, span) = source.lint();
127 span_lint_and_then(cx, lint, span, msg, |diag| {
128 if span.from_expansion() {
129 return; // Don't give suggestions into macros.
132 Source::Item { .. } => {
133 let const_kw_span = span.from_inner(InnerSpan::new(0, 5));
134 diag.span_label(const_kw_span, "make this a static item (maybe with lazy_static)");
136 Source::Assoc { .. } => (),
137 Source::Expr { .. } => {
138 diag.help("assign this const to a local or static variable, and use the variable here");
144 declare_lint_pass!(NonCopyConst => [DECLARE_INTERIOR_MUTABLE_CONST, BORROW_INTERIOR_MUTABLE_CONST]);
146 impl<'tcx> LateLintPass<'tcx> for NonCopyConst {
147 fn check_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx Item<'_>) {
148 if let ItemKind::Const(hir_ty, ..) = &it.kind {
149 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
150 verify_ty_bound(cx, ty, Source::Item { item: it.span });
154 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, trait_item: &'tcx TraitItem<'_>) {
155 if let TraitItemKind::Const(hir_ty, ..) = &trait_item.kind {
156 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
157 // Normalize assoc types because ones originated from generic params
158 // bounded other traits could have their bound.
159 let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
160 verify_ty_bound(cx, normalized, Source::Assoc { item: trait_item.span });
164 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx ImplItem<'_>) {
165 if let ImplItemKind::Const(hir_ty, ..) = &impl_item.kind {
166 let item_hir_id = cx.tcx.hir().get_parent_node(impl_item.hir_id);
167 let item = cx.tcx.hir().expect_item(item_hir_id);
171 of_trait: Some(of_trait_ref),
175 // Lint a trait impl item only when the definition is a generic type,
176 // assuming a assoc const is not meant to be a interior mutable type.
177 if let Some(of_trait_def_id) = of_trait_ref.trait_def_id();
178 if let Some(of_assoc_item) = specialization_graph::Node::Trait(of_trait_def_id)
179 .item(cx.tcx, impl_item.ident, AssocKind::Const, of_trait_def_id);
182 .layout_of(cx.tcx.param_env(of_trait_def_id).and(
183 // Normalize assoc types because ones originated from generic params
184 // bounded other traits could have their bound at the trait defs;
185 // and, in that case, the definition is *not* generic.
186 cx.tcx.normalize_erasing_regions(
187 cx.tcx.param_env(of_trait_def_id),
188 cx.tcx.type_of(of_assoc_item.def_id),
193 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
194 let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
199 item: impl_item.span,
205 ItemKind::Impl { of_trait: None, .. } => {
206 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
207 // Normalize assoc types originated from generic params.
208 let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
209 verify_ty_bound(cx, normalized, Source::Assoc { item: impl_item.span });
216 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
217 if let ExprKind::Path(qpath) = &expr.kind {
218 // Only lint if we use the const item inside a function.
219 if in_constant(cx, expr.hir_id) {
223 // Make sure it is a const item.
224 match qpath_res(cx, qpath, expr.hir_id) {
225 Res::Def(DefKind::Const | DefKind::AssocConst, _) => {},
229 // Climb up to resolve any field access and explicit referencing.
230 let mut cur_expr = expr;
231 let mut dereferenced_expr = expr;
232 let mut needs_check_adjustment = true;
234 let parent_id = cx.tcx.hir().get_parent_node(cur_expr.hir_id);
235 if parent_id == cur_expr.hir_id {
238 if let Some(Node::Expr(parent_expr)) = cx.tcx.hir().find(parent_id) {
239 match &parent_expr.kind {
240 ExprKind::AddrOf(..) => {
241 // `&e` => `e` must be referenced.
242 needs_check_adjustment = false;
244 ExprKind::Field(..) => {
245 needs_check_adjustment = true;
247 // Check whether implicit dereferences happened;
248 // if so, no need to go further up
249 // because of the same reason as the `ExprKind::Unary` case.
252 .expr_adjustments(dereferenced_expr)
254 .any(|adj| matches!(adj.kind, Adjust::Deref(_)))
259 dereferenced_expr = parent_expr;
261 ExprKind::Index(e, _) if ptr::eq(&**e, cur_expr) => {
262 // `e[i]` => desugared to `*Index::index(&e, i)`,
263 // meaning `e` must be referenced.
264 // no need to go further up since a method call is involved now.
265 needs_check_adjustment = false;
268 ExprKind::Unary(UnOp::UnDeref, _) => {
269 // `*e` => desugared to `*Deref::deref(&e)`,
270 // meaning `e` must be referenced.
271 // no need to go further up since a method call is involved now.
272 needs_check_adjustment = false;
277 cur_expr = parent_expr;
283 let ty = if needs_check_adjustment {
284 let adjustments = cx.typeck_results().expr_adjustments(dereferenced_expr);
285 if let Some(i) = adjustments
287 .position(|adj| matches!(adj.kind, Adjust::Borrow(_) | Adjust::Deref(_)))
290 cx.typeck_results().expr_ty(dereferenced_expr)
292 adjustments[i - 1].target
295 // No borrow adjustments means the entire const is moved.
299 cx.typeck_results().expr_ty(dereferenced_expr)
302 verify_ty_bound(cx, ty, Source::Expr { expr: expr.span });