1 //! Checks for uses of const which the type is not Freeze (Cell-free).
3 //! This lint is **deny** by default.
5 use rustc::lint::{LateContext, LateLintPass, Lint, LintArray, LintPass};
6 use rustc::{declare_tool_lint, lint_array};
8 use rustc::hir::def::Def;
9 use rustc::ty::{self, TypeFlags};
10 use rustc::ty::adjustment::Adjust;
11 use rustc_errors::Applicability;
12 use rustc_typeck::hir_ty_to_ty;
13 use syntax_pos::{DUMMY_SP, Span};
15 use crate::utils::{in_constant, in_macro, is_copy, span_lint_and_then};
17 /// **What it does:** Checks for declaration of `const` items which is interior
18 /// mutable (e.g. contains a `Cell`, `Mutex`, `AtomicXxxx` etc).
20 /// **Why is this bad?** Consts are copied everywhere they are referenced, i.e.
21 /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
22 /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
23 /// these types in the first place.
25 /// The `const` should better be replaced by a `static` item if a global
26 /// variable is wanted, or replaced by a `const fn` if a constructor is wanted.
28 /// **Known problems:** A "non-constant" const item is a legacy way to supply an
29 /// initialized value to downstream `static` items (e.g. the
30 /// `std::sync::ONCE_INIT` constant). In this case the use of `const` is legit,
31 /// and this lint should be suppressed.
35 /// use std::sync::atomic::{Ordering::SeqCst, AtomicUsize};
38 /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
39 /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
40 /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
43 /// static STATIC_ATOM: AtomicUsize = AtomicUsize::new(15);
44 /// STATIC_ATOM.store(9, SeqCst);
45 /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
47 declare_clippy_lint! {
48 pub DECLARE_INTERIOR_MUTABLE_CONST,
50 "declaring const with interior mutability"
53 /// **What it does:** Checks if `const` items which is interior mutable (e.g.
54 /// contains a `Cell`, `Mutex`, `AtomicXxxx` etc) has been borrowed directly.
56 /// **Why is this bad?** Consts are copied everywhere they are referenced, i.e.
57 /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
58 /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
59 /// these types in the first place.
61 /// The `const` value should be stored inside a `static` item.
63 /// **Known problems:** None
67 /// use std::sync::atomic::{Ordering::SeqCst, AtomicUsize};
68 /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
71 /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
72 /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
75 /// static STATIC_ATOM: AtomicUsize = CONST_ATOM;
76 /// STATIC_ATOM.store(9, SeqCst);
77 /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
79 declare_clippy_lint! {
80 pub BORROW_INTERIOR_MUTABLE_CONST,
82 "referencing const with interior mutability"
85 #[derive(Copy, Clone)]
100 fn lint(&self) -> (&'static Lint, &'static str, Span) {
102 Source::Item { item } | Source::Assoc { item, .. } => (
103 DECLARE_INTERIOR_MUTABLE_CONST,
104 "a const item should never be interior mutable",
107 Source::Expr { expr } => (
108 BORROW_INTERIOR_MUTABLE_CONST,
109 "a const item with interior mutability should not be borrowed",
116 fn verify_ty_bound<'a, 'tcx>(
117 cx: &LateContext<'a, 'tcx>,
121 if ty.is_freeze(cx.tcx, cx.param_env, DUMMY_SP) || is_copy(cx, ty) {
122 // an UnsafeCell is !Copy, and an UnsafeCell is also the only type which
123 // is !Freeze, thus if our type is Copy we can be sure it must be Freeze
128 let (lint, msg, span) = source.lint();
129 span_lint_and_then(cx, lint, span, msg, |db| {
131 return; // Don't give suggestions into macros.
134 Source::Item { .. } => {
135 let const_kw_span = span.from_inner_byte_pos(0, 5);
136 db.span_suggestion_with_applicability(
138 "make this a static item",
139 "static".to_string(),
140 Applicability::MachineApplicable,
143 Source::Assoc { ty: ty_span, .. } => {
144 if ty.flags.contains(TypeFlags::HAS_FREE_LOCAL_NAMES) {
145 db.span_help(ty_span, &format!("consider requiring `{}` to be `Copy`", ty));
148 Source::Expr { .. } => {
150 "assign this const to a local or static variable, and use the variable here",
158 pub struct NonCopyConst;
160 impl LintPass for NonCopyConst {
161 fn get_lints(&self) -> LintArray {
162 lint_array!(DECLARE_INTERIOR_MUTABLE_CONST, BORROW_INTERIOR_MUTABLE_CONST)
166 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCopyConst {
167 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, it: &'tcx Item) {
168 if let ItemKind::Const(hir_ty, ..) = &it.node {
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<'a, 'tcx>, trait_item: &'tcx TraitItem) {
175 if let TraitItemKind::Const(hir_ty, ..) = &trait_item.node {
176 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
177 verify_ty_bound(cx, ty, Source::Assoc { ty: hir_ty.span, item: trait_item.span });
181 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, impl_item: &'tcx ImplItem) {
182 if let ImplItemKind::Const(hir_ty, ..) = &impl_item.node {
183 let item_node_id = cx.tcx.hir.get_parent_node(impl_item.id);
184 let item = cx.tcx.hir.expect_item(item_node_id);
185 // ensure the impl is an inherent impl.
186 if let ItemKind::Impl(_, _, _, _, None, _, _) = item.node {
187 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
188 verify_ty_bound(cx, ty, Source::Assoc { ty: hir_ty.span, item: impl_item.span });
193 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
194 if let ExprKind::Path(qpath) = &expr.node {
195 // Only lint if we use the const item inside a function.
196 if in_constant(cx, expr.id) {
200 // make sure it is a const item.
201 match cx.tables.qpath_def(qpath, expr.hir_id) {
202 Def::Const(_) | Def::AssociatedConst(_) => {},
206 // climb up to resolve any field access and explicit referencing.
207 let mut cur_expr = expr;
208 let mut dereferenced_expr = expr;
209 let mut needs_check_adjustment = true;
211 let parent_id = cx.tcx.hir.get_parent_node(cur_expr.id);
212 if parent_id == cur_expr.id {
215 if let Some(Node::Expr(parent_expr)) = cx.tcx.hir.find(parent_id) {
216 match &parent_expr.node {
217 ExprKind::AddrOf(..) => {
218 // `&e` => `e` must be referenced
219 needs_check_adjustment = false;
221 ExprKind::Field(..) => {
222 dereferenced_expr = parent_expr;
223 needs_check_adjustment = true;
225 ExprKind::Index(e, _) if ptr::eq(&**e, cur_expr) => {
226 // `e[i]` => desugared to `*Index::index(&e, i)`,
227 // meaning `e` must be referenced.
228 // no need to go further up since a method call is involved now.
229 needs_check_adjustment = false;
232 ExprKind::Unary(UnDeref, _) => {
233 // `*e` => desugared to `*Deref::deref(&e)`,
234 // meaning `e` must be referenced.
235 // no need to go further up since a method call is involved now.
236 needs_check_adjustment = false;
241 cur_expr = parent_expr;
247 let ty = if needs_check_adjustment {
248 let adjustments = cx.tables.expr_adjustments(dereferenced_expr);
249 if let Some(i) = adjustments.iter().position(|adj| match adj.kind {
250 Adjust::Borrow(_) | Adjust::Deref(_) => true,
254 cx.tables.expr_ty(dereferenced_expr)
256 adjustments[i - 1].target
259 // No borrow adjustments = the entire const is moved.
263 cx.tables.expr_ty(dereferenced_expr)
266 verify_ty_bound(cx, ty, Source::Expr { expr: expr.span });