1 //! Checks for uses of const which the type is not Freeze (Cell-free).
3 //! This lint is **deny** by default.
5 use crate::utils::{in_constant, in_macro, is_copy, span_lint_and_then};
6 use rustc::hir::def::Def;
8 use rustc::lint::{LateContext, LateLintPass, Lint, LintArray, LintPass};
9 use rustc::ty::adjustment::Adjust;
10 use rustc::ty::{self, TypeFlags};
11 use rustc::{declare_tool_lint, lint_array};
12 use rustc_errors::Applicability;
13 use rustc_typeck::hir_ty_to_ty;
15 use syntax_pos::{Span, DUMMY_SP};
17 declare_clippy_lint! {
18 /// **What it does:** Checks for declaration of `const` items which is interior
19 /// mutable (e.g. contains a `Cell`, `Mutex`, `AtomicXxxx` etc).
21 /// **Why is this bad?** Consts are copied everywhere they are referenced, i.e.
22 /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
23 /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
24 /// these types in the first place.
26 /// The `const` should better be replaced by a `static` item if a global
27 /// variable is wanted, or replaced by a `const fn` if a constructor is wanted.
29 /// **Known problems:** A "non-constant" const item is a legacy way to supply an
30 /// initialized value to downstream `static` items (e.g. the
31 /// `std::sync::ONCE_INIT` constant). In this case the use of `const` is legit,
32 /// and this lint should be suppressed.
36 /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
39 /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
40 /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
41 /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
44 /// static STATIC_ATOM: AtomicUsize = AtomicUsize::new(15);
45 /// STATIC_ATOM.store(9, SeqCst);
46 /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
48 pub DECLARE_INTERIOR_MUTABLE_CONST,
50 "declaring const with interior mutability"
53 declare_clippy_lint! {
54 /// **What it does:** Checks if `const` items which is interior mutable (e.g.
55 /// contains a `Cell`, `Mutex`, `AtomicXxxx` etc) has been borrowed directly.
57 /// **Why is this bad?** Consts are copied everywhere they are referenced, i.e.
58 /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
59 /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
60 /// these types in the first place.
62 /// The `const` value should be stored inside a `static` item.
64 /// **Known problems:** None
68 /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
69 /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
72 /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
73 /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
76 /// static STATIC_ATOM: AtomicUsize = CONST_ATOM;
77 /// STATIC_ATOM.store(9, SeqCst);
78 /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
80 pub BORROW_INTERIOR_MUTABLE_CONST,
82 "referencing const with interior mutability"
85 #[derive(Copy, Clone)]
88 Assoc { item: Span, ty: Span },
93 fn lint(&self) -> (&'static Lint, &'static str, Span) {
95 Source::Item { item } | Source::Assoc { item, .. } => (
96 DECLARE_INTERIOR_MUTABLE_CONST,
97 "a const item should never be interior mutable",
100 Source::Expr { expr } => (
101 BORROW_INTERIOR_MUTABLE_CONST,
102 "a const item with interior mutability should not be borrowed",
109 fn verify_ty_bound<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: ty::Ty<'tcx>, source: Source) {
110 if ty.is_freeze(cx.tcx, cx.param_env, DUMMY_SP) || is_copy(cx, ty) {
111 // an UnsafeCell is !Copy, and an UnsafeCell is also the only type which
112 // is !Freeze, thus if our type is Copy we can be sure it must be Freeze
117 let (lint, msg, span) = source.lint();
118 span_lint_and_then(cx, lint, span, msg, |db| {
120 return; // Don't give suggestions into macros.
123 Source::Item { .. } => {
124 let const_kw_span = span.from_inner_byte_pos(0, 5);
127 "make this a static item",
128 "static".to_string(),
129 Applicability::MachineApplicable,
132 Source::Assoc { ty: ty_span, .. } => {
133 if ty.flags.contains(TypeFlags::HAS_FREE_LOCAL_NAMES) {
134 db.span_help(ty_span, &format!("consider requiring `{}` to be `Copy`", ty));
137 Source::Expr { .. } => {
138 db.help("assign this const to a local or static variable, and use the variable here");
144 pub struct NonCopyConst;
146 impl LintPass for NonCopyConst {
147 fn get_lints(&self) -> LintArray {
148 lint_array!(DECLARE_INTERIOR_MUTABLE_CONST, BORROW_INTERIOR_MUTABLE_CONST)
151 fn name(&self) -> &'static str {
156 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCopyConst {
157 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, it: &'tcx Item) {
158 if let ItemKind::Const(hir_ty, ..) = &it.node {
159 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
160 verify_ty_bound(cx, ty, Source::Item { item: it.span });
164 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, trait_item: &'tcx TraitItem) {
165 if let TraitItemKind::Const(hir_ty, ..) = &trait_item.node {
166 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
172 item: trait_item.span,
178 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, impl_item: &'tcx ImplItem) {
179 if let ImplItemKind::Const(hir_ty, ..) = &impl_item.node {
180 let item_hir_id = cx.tcx.hir().get_parent_node_by_hir_id(impl_item.hir_id);
181 let item = cx.tcx.hir().expect_item_by_hir_id(item_hir_id);
182 // ensure the impl is an inherent impl.
183 if let ItemKind::Impl(_, _, _, _, None, _, _) = item.node {
184 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
190 item: impl_item.span,
197 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
198 if let ExprKind::Path(qpath) = &expr.node {
199 // Only lint if we use the const item inside a function.
200 if in_constant(cx, expr.hir_id) {
204 // make sure it is a const item.
205 match cx.tables.qpath_def(qpath, expr.hir_id) {
206 Def::Const(_) | Def::AssociatedConst(_) => {},
210 // climb up to resolve any field access and explicit referencing.
211 let mut cur_expr = expr;
212 let mut dereferenced_expr = expr;
213 let mut needs_check_adjustment = true;
215 let parent_id = cx.tcx.hir().get_parent_node_by_hir_id(cur_expr.hir_id);
216 if parent_id == cur_expr.hir_id {
219 if let Some(Node::Expr(parent_expr)) = cx.tcx.hir().find_by_hir_id(parent_id) {
220 match &parent_expr.node {
221 ExprKind::AddrOf(..) => {
222 // `&e` => `e` must be referenced
223 needs_check_adjustment = false;
225 ExprKind::Field(..) => {
226 dereferenced_expr = parent_expr;
227 needs_check_adjustment = true;
229 ExprKind::Index(e, _) if ptr::eq(&**e, cur_expr) => {
230 // `e[i]` => desugared to `*Index::index(&e, i)`,
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;
236 ExprKind::Unary(UnDeref, _) => {
237 // `*e` => desugared to `*Deref::deref(&e)`,
238 // meaning `e` must be referenced.
239 // no need to go further up since a method call is involved now.
240 needs_check_adjustment = false;
245 cur_expr = parent_expr;
251 let ty = if needs_check_adjustment {
252 let adjustments = cx.tables.expr_adjustments(dereferenced_expr);
253 if let Some(i) = adjustments.iter().position(|adj| match adj.kind {
254 Adjust::Borrow(_) | Adjust::Deref(_) => true,
258 cx.tables.expr_ty(dereferenced_expr)
260 adjustments[i - 1].target
263 // No borrow adjustments = the entire const is moved.
267 cx.tables.expr_ty(dereferenced_expr)
270 verify_ty_bound(cx, ty, Source::Expr { expr: expr.span });