]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/non_copy_const.rs
039de766c086a91b6b3c093aad8dee5e14c1826f
[rust.git] / clippy_lints / src / non_copy_const.rs
1 //! Checks for uses of const which the type is not `Freeze` (`Cell`-free).
2 //!
3 //! This lint is **deny** by default.
4
5 use std::ptr;
6
7 use rustc::declare_lint_pass;
8 use rustc::lint::{LateContext, LateLintPass, Lint, LintArray, LintPass};
9 use rustc::ty::adjustment::Adjust;
10 use rustc::ty::{Ty, TypeFlags};
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::*;
13 use rustc_session::declare_tool_lint;
14 use rustc_span::{InnerSpan, Span, DUMMY_SP};
15 use rustc_typeck::hir_ty_to_ty;
16
17 use crate::utils::{in_constant, is_copy, qpath_res, span_lint_and_then};
18
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.).
22     ///
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.
27     ///
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.
30     ///
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.
35     ///
36     /// **Example:**
37     /// ```rust
38     /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
39     ///
40     /// // Bad.
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
44     ///
45     /// // Good.
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
49     /// ```
50     pub DECLARE_INTERIOR_MUTABLE_CONST,
51     correctness,
52     "declaring const with interior mutability"
53 }
54
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.
58     ///
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.
63     ///
64     /// The `const` value should be stored inside a `static` item.
65     ///
66     /// **Known problems:** None
67     ///
68     /// **Example:**
69     /// ```rust
70     /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
71     /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
72     ///
73     /// // Bad.
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
76     ///
77     /// // Good.
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
81     /// ```
82     pub BORROW_INTERIOR_MUTABLE_CONST,
83     correctness,
84     "referencing const with interior mutability"
85 }
86
87 #[allow(dead_code)]
88 #[derive(Copy, Clone)]
89 enum Source {
90     Item { item: Span },
91     Assoc { item: Span, ty: Span },
92     Expr { expr: Span },
93 }
94
95 impl Source {
96     #[must_use]
97     fn lint(&self) -> (&'static Lint, &'static str, Span) {
98         match self {
99             Self::Item { item } | Self::Assoc { item, .. } => (
100                 DECLARE_INTERIOR_MUTABLE_CONST,
101                 "a const item should never be interior mutable",
102                 *item,
103             ),
104             Self::Expr { expr } => (
105                 BORROW_INTERIOR_MUTABLE_CONST,
106                 "a const item with interior mutability should not be borrowed",
107                 *expr,
108             ),
109         }
110     }
111 }
112
113 fn verify_ty_bound<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>, source: Source) {
114     if ty.is_freeze(cx.tcx, cx.param_env, DUMMY_SP) || is_copy(cx, ty) {
115         // An `UnsafeCell` is `!Copy`, and an `UnsafeCell` is also the only type which
116         // is `!Freeze`, thus if our type is `Copy` we can be sure it must be `Freeze`
117         // as well.
118         return;
119     }
120
121     let (lint, msg, span) = source.lint();
122     span_lint_and_then(cx, lint, span, msg, |db| {
123         if span.from_expansion() {
124             return; // Don't give suggestions into macros.
125         }
126         match source {
127             Source::Item { .. } => {
128                 let const_kw_span = span.from_inner(InnerSpan::new(0, 5));
129                 db.span_label(const_kw_span, "make this a static item (maybe with lazy_static)");
130             },
131             Source::Assoc { ty: ty_span, .. } => {
132                 if ty.flags.contains(TypeFlags::HAS_FREE_LOCAL_NAMES) {
133                     db.span_label(ty_span, &format!("consider requiring `{}` to be `Copy`", ty));
134                 }
135             },
136             Source::Expr { .. } => {
137                 db.help("assign this const to a local or static variable, and use the variable here");
138             },
139         }
140     });
141 }
142
143 declare_lint_pass!(NonCopyConst => [DECLARE_INTERIOR_MUTABLE_CONST, BORROW_INTERIOR_MUTABLE_CONST]);
144
145 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCopyConst {
146     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, it: &'tcx Item<'_>) {
147         if let ItemKind::Const(hir_ty, ..) = &it.kind {
148             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
149             verify_ty_bound(cx, ty, Source::Item { item: it.span });
150         }
151     }
152
153     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, trait_item: &'tcx TraitItem<'_>) {
154         if let TraitItemKind::Const(hir_ty, ..) = &trait_item.kind {
155             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
156             verify_ty_bound(
157                 cx,
158                 ty,
159                 Source::Assoc {
160                     ty: hir_ty.span,
161                     item: trait_item.span,
162                 },
163             );
164         }
165     }
166
167     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, impl_item: &'tcx ImplItem<'_>) {
168         if let ImplItemKind::Const(hir_ty, ..) = &impl_item.kind {
169             let item_hir_id = cx.tcx.hir().get_parent_node(impl_item.hir_id);
170             let item = cx.tcx.hir().expect_item(item_hir_id);
171             // Ensure the impl is an inherent impl.
172             if let ItemKind::Impl(_, _, _, _, None, _, _) = item.kind {
173                 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
174                 verify_ty_bound(
175                     cx,
176                     ty,
177                     Source::Assoc {
178                         ty: hir_ty.span,
179                         item: impl_item.span,
180                     },
181                 );
182             }
183         }
184     }
185
186     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
187         if let ExprKind::Path(qpath) = &expr.kind {
188             // Only lint if we use the const item inside a function.
189             if in_constant(cx, expr.hir_id) {
190                 return;
191             }
192
193             // Make sure it is a const item.
194             match qpath_res(cx, qpath, expr.hir_id) {
195                 Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) => {},
196                 _ => return,
197             };
198
199             // Climb up to resolve any field access and explicit referencing.
200             let mut cur_expr = expr;
201             let mut dereferenced_expr = expr;
202             let mut needs_check_adjustment = true;
203             loop {
204                 let parent_id = cx.tcx.hir().get_parent_node(cur_expr.hir_id);
205                 if parent_id == cur_expr.hir_id {
206                     break;
207                 }
208                 if let Some(Node::Expr(parent_expr)) = cx.tcx.hir().find(parent_id) {
209                     match &parent_expr.kind {
210                         ExprKind::AddrOf(..) => {
211                             // `&e` => `e` must be referenced.
212                             needs_check_adjustment = false;
213                         },
214                         ExprKind::Field(..) => {
215                             dereferenced_expr = parent_expr;
216                             needs_check_adjustment = true;
217                         },
218                         ExprKind::Index(e, _) if ptr::eq(&**e, cur_expr) => {
219                             // `e[i]` => desugared to `*Index::index(&e, i)`,
220                             // meaning `e` must be referenced.
221                             // no need to go further up since a method call is involved now.
222                             needs_check_adjustment = false;
223                             break;
224                         },
225                         ExprKind::Unary(UnOp::UnDeref, _) => {
226                             // `*e` => desugared to `*Deref::deref(&e)`,
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;
230                             break;
231                         },
232                         _ => break,
233                     }
234                     cur_expr = parent_expr;
235                 } else {
236                     break;
237                 }
238             }
239
240             let ty = if needs_check_adjustment {
241                 let adjustments = cx.tables.expr_adjustments(dereferenced_expr);
242                 if let Some(i) = adjustments.iter().position(|adj| match adj.kind {
243                     Adjust::Borrow(_) | Adjust::Deref(_) => true,
244                     _ => false,
245                 }) {
246                     if i == 0 {
247                         cx.tables.expr_ty(dereferenced_expr)
248                     } else {
249                         adjustments[i - 1].target
250                     }
251                 } else {
252                     // No borrow adjustments means the entire const is moved.
253                     return;
254                 }
255             } else {
256                 cx.tables.expr_ty(dereferenced_expr)
257             };
258
259             verify_ty_bound(cx, ty, Source::Expr { expr: expr.span });
260         }
261     }
262 }