]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/non_copy_const.rs
Change the criteria of `interior_mutable_const`
[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_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::fold::TypeFoldable as _;
13 use rustc_middle::ty::{AssocKind, Ty, TypeFlags};
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
15 use rustc_span::{InnerSpan, Span, DUMMY_SP};
16 use rustc_typeck::hir_ty_to_ty;
17
18 use crate::utils::{in_constant, qpath_res, span_lint_and_then};
19 use if_chain::if_chain;
20
21 declare_clippy_lint! {
22     /// **What it does:** Checks for declaration of `const` items which is interior
23     /// mutable (e.g., contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.).
24     ///
25     /// **Why is this bad?** Consts are copied everywhere they are referenced, i.e.,
26     /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
27     /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
28     /// these types in the first place.
29     ///
30     /// The `const` should better be replaced by a `static` item if a global
31     /// variable is wanted, or replaced by a `const fn` if a constructor is wanted.
32     ///
33     /// **Known problems:** A "non-constant" const item is a legacy way to supply an
34     /// initialized value to downstream `static` items (e.g., the
35     /// `std::sync::ONCE_INIT` constant). In this case the use of `const` is legit,
36     /// and this lint should be suppressed.
37     ///
38     /// **Example:**
39     /// ```rust
40     /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
41     ///
42     /// // Bad.
43     /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
44     /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
45     /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
46     ///
47     /// // Good.
48     /// static STATIC_ATOM: AtomicUsize = AtomicUsize::new(15);
49     /// STATIC_ATOM.store(9, SeqCst);
50     /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
51     /// ```
52     pub DECLARE_INTERIOR_MUTABLE_CONST,
53     correctness,
54     "declaring `const` with interior mutability"
55 }
56
57 declare_clippy_lint! {
58     /// **What it does:** Checks if `const` items which is interior mutable (e.g.,
59     /// contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.) has been borrowed directly.
60     ///
61     /// **Why is this bad?** Consts are copied everywhere they are referenced, i.e.,
62     /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
63     /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
64     /// these types in the first place.
65     ///
66     /// The `const` value should be stored inside a `static` item.
67     ///
68     /// **Known problems:** None
69     ///
70     /// **Example:**
71     /// ```rust
72     /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
73     /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
74     ///
75     /// // Bad.
76     /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
77     /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
78     ///
79     /// // Good.
80     /// static STATIC_ATOM: AtomicUsize = CONST_ATOM;
81     /// STATIC_ATOM.store(9, SeqCst);
82     /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
83     /// ```
84     pub BORROW_INTERIOR_MUTABLE_CONST,
85     correctness,
86     "referencing `const` with interior mutability"
87 }
88
89 #[derive(Copy, Clone)]
90 enum Source {
91     Item { item: Span },
92     Assoc { item: Span },
93     Expr { expr: Span },
94 }
95
96 impl Source {
97     #[must_use]
98     fn lint(&self) -> (&'static Lint, &'static str, Span) {
99         match self {
100             Self::Item { item } | Self::Assoc { item, .. } => (
101                 DECLARE_INTERIOR_MUTABLE_CONST,
102                 "a `const` item should never be interior mutable",
103                 *item,
104             ),
105             Self::Expr { expr } => (
106                 BORROW_INTERIOR_MUTABLE_CONST,
107                 "a `const` item with interior mutability should not be borrowed",
108                 *expr,
109             ),
110         }
111     }
112 }
113
114 fn verify_ty_bound<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, source: Source) {
115     // Ignore types whose layout is unknown since `is_freeze` reports every generic types as `!Freeze`,
116     // making it indistinguishable from `UnsafeCell`. i.e. it isn't a tool to prove a type is
117     // 'unfrozen'. However, this code causes a false negative in which
118     // a type contains a layout-unknown type, but also a unsafe cell like `const CELL: Cell<T>`.
119     // Yet, it's better than `ty.has_type_flags(TypeFlags::HAS_TY_PARAM | TypeFlags::HAS_PROJECTION)`
120     // since it works when a pointer indirection involves (`Cell<*const T>`).
121     // Making up a `ParamEnv` where every generic params and assoc types are `Freeze`is another option;
122     // but I'm not sure whether it's a decent way, if possible.
123     if cx.tcx.layout_of(cx.param_env.and(ty)).is_err() || ty.is_freeze(cx.tcx.at(DUMMY_SP), cx.param_env) {
124         return;
125     }
126
127     let (lint, msg, span) = source.lint();
128     span_lint_and_then(cx, lint, span, msg, |diag| {
129         if span.from_expansion() {
130             return; // Don't give suggestions into macros.
131         }
132         match source {
133             Source::Item { .. } => {
134                 let const_kw_span = span.from_inner(InnerSpan::new(0, 5));
135                 diag.span_label(const_kw_span, "make this a static item (maybe with lazy_static)");
136             },
137             Source::Assoc { .. } => (),
138             Source::Expr { .. } => {
139                 diag.help("assign this const to a local or static variable, and use the variable here");
140             },
141         }
142     });
143 }
144
145 declare_lint_pass!(NonCopyConst => [DECLARE_INTERIOR_MUTABLE_CONST, BORROW_INTERIOR_MUTABLE_CONST]);
146
147 impl<'tcx> LateLintPass<'tcx> for NonCopyConst {
148     fn check_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx Item<'_>) {
149         if let ItemKind::Const(hir_ty, ..) = &it.kind {
150             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
151             verify_ty_bound(cx, ty, Source::Item { item: it.span });
152         }
153     }
154
155     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, trait_item: &'tcx TraitItem<'_>) {
156         if let TraitItemKind::Const(hir_ty, ..) = &trait_item.kind {
157             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
158             // Normalize assoc types because ones originated from generic params
159             // bounded other traits could have their bound.
160             let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
161             verify_ty_bound(cx, normalized, Source::Assoc { item: trait_item.span });
162         }
163     }
164
165     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx ImplItem<'_>) {
166         if let ImplItemKind::Const(hir_ty, ..) = &impl_item.kind {
167             let item_hir_id = cx.tcx.hir().get_parent_node(impl_item.hir_id);
168             let item = cx.tcx.hir().expect_item(item_hir_id);
169
170             match &item.kind {
171                 ItemKind::Impl {
172                     of_trait: Some(of_trait_ref),
173                     ..
174                 } => {
175                     if_chain! {
176                         // Lint a trait impl item only when the definition is a generic type,
177                         // assuming a assoc const is not meant to be a interior mutable type.
178                         if let Some(of_trait_def_id) = of_trait_ref.trait_def_id();
179                         if let Some(of_assoc_item) = specialization_graph::Node::Trait(of_trait_def_id)
180                             .item(cx.tcx, impl_item.ident, AssocKind::Const, of_trait_def_id);
181                         if cx.tcx
182                             // Normalize assoc types because ones originated from generic params
183                             // bounded other traits could have their bound at the trait defs;
184                             // and, in that case, the definition is *not* generic.
185                             .normalize_erasing_regions(
186                                 cx.tcx.param_env(of_trait_def_id),
187                                 cx.tcx.type_of(of_assoc_item.def_id),
188                             )
189                             .has_type_flags(TypeFlags::HAS_PROJECTION | TypeFlags::HAS_TY_PARAM);
190                         then {
191                             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
192                             let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
193                             verify_ty_bound(
194                                 cx,
195                                 normalized,
196                                 Source::Assoc {
197                                     item: impl_item.span,
198                                 },
199                             );
200                         }
201                     }
202                 },
203                 ItemKind::Impl { of_trait: None, .. } => {
204                     let ty = hir_ty_to_ty(cx.tcx, hir_ty);
205                     // Normalize assoc types originated from generic params.
206                     let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
207                     verify_ty_bound(cx, normalized, Source::Assoc { item: impl_item.span });
208                 },
209                 _ => (),
210             }
211         }
212     }
213
214     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
215         if let ExprKind::Path(qpath) = &expr.kind {
216             // Only lint if we use the const item inside a function.
217             if in_constant(cx, expr.hir_id) {
218                 return;
219             }
220
221             // Make sure it is a const item.
222             match qpath_res(cx, qpath, expr.hir_id) {
223                 Res::Def(DefKind::Const | DefKind::AssocConst, _) => {},
224                 _ => return,
225             };
226
227             // Climb up to resolve any field access and explicit referencing.
228             let mut cur_expr = expr;
229             let mut dereferenced_expr = expr;
230             let mut needs_check_adjustment = true;
231             loop {
232                 let parent_id = cx.tcx.hir().get_parent_node(cur_expr.hir_id);
233                 if parent_id == cur_expr.hir_id {
234                     break;
235                 }
236                 if let Some(Node::Expr(parent_expr)) = cx.tcx.hir().find(parent_id) {
237                     match &parent_expr.kind {
238                         ExprKind::AddrOf(..) => {
239                             // `&e` => `e` must be referenced.
240                             needs_check_adjustment = false;
241                         },
242                         ExprKind::Field(..) => {
243                             needs_check_adjustment = true;
244
245                             // Check whether implicit dereferences happened;
246                             // if so, no need to go further up
247                             // because of the same reason as the `ExprKind::Unary` case.
248                             if cx
249                                 .typeck_results()
250                                 .expr_adjustments(dereferenced_expr)
251                                 .iter()
252                                 .any(|adj| matches!(adj.kind, Adjust::Deref(_)))
253                             {
254                                 break;
255                             }
256
257                             dereferenced_expr = parent_expr;
258                         },
259                         ExprKind::Index(e, _) if ptr::eq(&**e, cur_expr) => {
260                             // `e[i]` => desugared to `*Index::index(&e, i)`,
261                             // meaning `e` must be referenced.
262                             // no need to go further up since a method call is involved now.
263                             needs_check_adjustment = false;
264                             break;
265                         },
266                         ExprKind::Unary(UnOp::UnDeref, _) => {
267                             // `*e` => desugared to `*Deref::deref(&e)`,
268                             // meaning `e` must be referenced.
269                             // no need to go further up since a method call is involved now.
270                             needs_check_adjustment = false;
271                             break;
272                         },
273                         _ => break,
274                     }
275                     cur_expr = parent_expr;
276                 } else {
277                     break;
278                 }
279             }
280
281             let ty = if needs_check_adjustment {
282                 let adjustments = cx.typeck_results().expr_adjustments(dereferenced_expr);
283                 if let Some(i) = adjustments
284                     .iter()
285                     .position(|adj| matches!(adj.kind, Adjust::Borrow(_) | Adjust::Deref(_)))
286                 {
287                     if i == 0 {
288                         cx.typeck_results().expr_ty(dereferenced_expr)
289                     } else {
290                         adjustments[i - 1].target
291                     }
292                 } else {
293                     // No borrow adjustments means the entire const is moved.
294                     return;
295                 }
296             } else {
297                 cx.typeck_results().expr_ty(dereferenced_expr)
298             };
299
300             verify_ty_bound(cx, ty, Source::Expr { expr: expr.span });
301         }
302     }
303 }