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