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};
9 use rustc::lint::{LateContext, LateLintPass, Lint, LintArray, LintPass};
10 use rustc::ty::adjustment::Adjust;
11 use rustc::ty::{Ty, TypeFlags};
12 use rustc::{declare_lint_pass, declare_tool_lint};
13 use rustc_errors::Applicability;
14 use rustc_typeck::hir_ty_to_ty;
15 use syntax_pos::{InnerSpan, Span, DUMMY_SP};
17 use crate::utils::{in_constant, is_copy, span_lint_and_then};
19 declare_clippy_lint! {
20 /// **What it does:** Checks for declaration of `const` items which is interior
21 /// mutable (e.g., contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.).
23 /// **Why is this bad?** Consts are copied everywhere they are referenced, i.e.,
24 /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
25 /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
26 /// these types in the first place.
28 /// The `const` should better be replaced by a `static` item if a global
29 /// variable is wanted, or replaced by a `const fn` if a constructor is wanted.
31 /// **Known problems:** A "non-constant" const item is a legacy way to supply an
32 /// initialized value to downstream `static` items (e.g., the
33 /// `std::sync::ONCE_INIT` constant). In this case the use of `const` is legit,
34 /// and this lint should be suppressed.
38 /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
41 /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
42 /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
43 /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
46 /// static STATIC_ATOM: AtomicUsize = AtomicUsize::new(15);
47 /// STATIC_ATOM.store(9, SeqCst);
48 /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
50 pub DECLARE_INTERIOR_MUTABLE_CONST,
52 "declaring const with interior mutability"
55 declare_clippy_lint! {
56 /// **What it does:** Checks if `const` items which is interior mutable (e.g.,
57 /// contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.) has been borrowed directly.
59 /// **Why is this bad?** Consts are copied everywhere they are referenced, i.e.,
60 /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
61 /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
62 /// these types in the first place.
64 /// The `const` value should be stored inside a `static` item.
66 /// **Known problems:** None
70 /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
71 /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
74 /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
75 /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
78 /// static STATIC_ATOM: AtomicUsize = CONST_ATOM;
79 /// STATIC_ATOM.store(9, SeqCst);
80 /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
82 pub BORROW_INTERIOR_MUTABLE_CONST,
84 "referencing const with interior mutability"
88 #[derive(Copy, Clone)]
91 Assoc { item: Span, ty: Span },
96 fn lint(&self) -> (&'static Lint, &'static str, Span) {
98 Self::Item { item } | Self::Assoc { item, .. } => (
99 DECLARE_INTERIOR_MUTABLE_CONST,
100 "a const item should never be interior mutable",
103 Self::Expr { expr } => (
104 BORROW_INTERIOR_MUTABLE_CONST,
105 "a const item with interior mutability should not be borrowed",
112 fn verify_ty_bound<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>, source: Source) {
113 if ty.is_freeze(cx.tcx, cx.param_env, DUMMY_SP) || is_copy(cx, ty) {
114 // An `UnsafeCell` is `!Copy`, and an `UnsafeCell` is also the only type which
115 // is `!Freeze`, thus if our type is `Copy` we can be sure it must be `Freeze`
120 let (lint, msg, span) = source.lint();
121 span_lint_and_then(cx, lint, span, msg, |db| {
122 if span.from_expansion() {
123 return; // Don't give suggestions into macros.
126 Source::Item { .. } => {
127 let const_kw_span = span.from_inner(InnerSpan::new(0, 5));
130 "make this a static item",
131 "static".to_string(),
132 Applicability::MachineApplicable,
135 Source::Assoc { ty: ty_span, .. } => {
136 if ty.flags.contains(TypeFlags::HAS_FREE_LOCAL_NAMES) {
137 db.span_help(ty_span, &format!("consider requiring `{}` to be `Copy`", ty));
140 Source::Expr { .. } => {
141 db.help("assign this const to a local or static variable, and use the variable here");
147 declare_lint_pass!(NonCopyConst => [DECLARE_INTERIOR_MUTABLE_CONST, BORROW_INTERIOR_MUTABLE_CONST]);
149 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCopyConst {
150 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, it: &'tcx Item) {
151 if let ItemKind::Const(hir_ty, ..) = &it.node {
152 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
153 verify_ty_bound(cx, ty, Source::Item { item: it.span });
157 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, trait_item: &'tcx TraitItem) {
158 if let TraitItemKind::Const(hir_ty, ..) = &trait_item.node {
159 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
165 item: trait_item.span,
171 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, impl_item: &'tcx ImplItem) {
172 if let ImplItemKind::Const(hir_ty, ..) = &impl_item.node {
173 let item_hir_id = cx.tcx.hir().get_parent_node(impl_item.hir_id);
174 let item = cx.tcx.hir().expect_item(item_hir_id);
175 // Ensure the impl is an inherent impl.
176 if let ItemKind::Impl(_, _, _, _, None, _, _) = item.node {
177 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
183 item: impl_item.span,
190 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
191 if let ExprKind::Path(qpath) = &expr.node {
192 // Only lint if we use the const item inside a function.
193 if in_constant(cx, expr.hir_id) {
197 // Make sure it is a const item.
198 match cx.tables.qpath_res(qpath, expr.hir_id) {
199 Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) => {},
203 // Climb up to resolve any field access and explicit referencing.
204 let mut cur_expr = expr;
205 let mut dereferenced_expr = expr;
206 let mut needs_check_adjustment = true;
208 let parent_id = cx.tcx.hir().get_parent_node(cur_expr.hir_id);
209 if parent_id == cur_expr.hir_id {
212 if let Some(Node::Expr(parent_expr)) = cx.tcx.hir().find(parent_id) {
213 match &parent_expr.node {
214 ExprKind::AddrOf(..) => {
215 // `&e` => `e` must be referenced.
216 needs_check_adjustment = false;
218 ExprKind::Field(..) => {
219 dereferenced_expr = parent_expr;
220 needs_check_adjustment = true;
222 ExprKind::Index(e, _) if ptr::eq(&**e, cur_expr) => {
223 // `e[i]` => desugared to `*Index::index(&e, i)`,
224 // meaning `e` must be referenced.
225 // no need to go further up since a method call is involved now.
226 needs_check_adjustment = false;
229 ExprKind::Unary(UnDeref, _) => {
230 // `*e` => desugared to `*Deref::deref(&e)`,
231 // meaning `e` must be referenced.
232 // no need to go further up since a method call is involved now.
233 needs_check_adjustment = false;
238 cur_expr = parent_expr;
244 let ty = if needs_check_adjustment {
245 let adjustments = cx.tables.expr_adjustments(dereferenced_expr);
246 if let Some(i) = adjustments.iter().position(|adj| match adj.kind {
247 Adjust::Borrow(_) | Adjust::Deref(_) => true,
251 cx.tables.expr_ty(dereferenced_expr)
253 adjustments[i - 1].target
256 // No borrow adjustments means the entire const is moved.
260 cx.tables.expr_ty(dereferenced_expr)
263 verify_ty_bound(cx, ty, Source::Expr { expr: expr.span });