]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/non_copy_const.rs
Auto merge of #9963 - ehuss:highfive-triagebot, r=xFrednet
[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 clippy_utils::diagnostics::span_lint_and_then;
8 use clippy_utils::in_constant;
9 use clippy_utils::macros::macro_backtrace;
10 use if_chain::if_chain;
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::def_id::DefId;
13 use rustc_hir::{
14     BodyId, Expr, ExprKind, HirId, Impl, ImplItem, ImplItemKind, Item, ItemKind, Node, TraitItem, TraitItemKind, UnOp,
15 };
16 use rustc_hir_analysis::hir_ty_to_ty;
17 use rustc_lint::{LateContext, LateLintPass, Lint};
18 use rustc_middle::mir;
19 use rustc_middle::mir::interpret::{ConstValue, ErrorHandled};
20 use rustc_middle::ty::adjustment::Adjust;
21 use rustc_middle::ty::{self, Ty};
22 use rustc_session::{declare_lint_pass, declare_tool_lint};
23 use rustc_span::{sym, InnerSpan, Span};
24
25 // FIXME: this is a correctness problem but there's no suitable
26 // warn-by-default category.
27 declare_clippy_lint! {
28     /// ### What it does
29     /// Checks for declaration of `const` items which is interior
30     /// mutable (e.g., contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.).
31     ///
32     /// ### Why is this bad?
33     /// Consts are copied everywhere they are referenced, i.e.,
34     /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
35     /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
36     /// these types in the first place.
37     ///
38     /// The `const` should better be replaced by a `static` item if a global
39     /// variable is wanted, or replaced by a `const fn` if a constructor is wanted.
40     ///
41     /// ### Known problems
42     /// A "non-constant" const item is a legacy way to supply an
43     /// initialized value to downstream `static` items (e.g., the
44     /// `std::sync::ONCE_INIT` constant). In this case the use of `const` is legit,
45     /// and this lint should be suppressed.
46     ///
47     /// Even though the lint avoids triggering on a constant whose type has enums that have variants
48     /// with interior mutability, and its value uses non interior mutable variants (see
49     /// [#3962](https://github.com/rust-lang/rust-clippy/issues/3962) and
50     /// [#3825](https://github.com/rust-lang/rust-clippy/issues/3825) for examples);
51     /// it complains about associated constants without default values only based on its types;
52     /// which might not be preferable.
53     /// There're other enums plus associated constants cases that the lint cannot handle.
54     ///
55     /// Types that have underlying or potential interior mutability trigger the lint whether
56     /// the interior mutable field is used or not. See issues
57     /// [#5812](https://github.com/rust-lang/rust-clippy/issues/5812) and
58     ///
59     /// ### Example
60     /// ```rust
61     /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
62     ///
63     /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
64     /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
65     /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
66     /// ```
67     ///
68     /// Use instead:
69     /// ```rust
70     /// # use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
71     /// static STATIC_ATOM: AtomicUsize = AtomicUsize::new(15);
72     /// STATIC_ATOM.store(9, SeqCst);
73     /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
74     /// ```
75     #[clippy::version = "pre 1.29.0"]
76     pub DECLARE_INTERIOR_MUTABLE_CONST,
77     style,
78     "declaring `const` with interior mutability"
79 }
80
81 // FIXME: this is a correctness problem but there's no suitable
82 // warn-by-default category.
83 declare_clippy_lint! {
84     /// ### What it does
85     /// Checks if `const` items which is interior mutable (e.g.,
86     /// contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.) has been borrowed directly.
87     ///
88     /// ### Why is this bad?
89     /// Consts are copied everywhere they are referenced, i.e.,
90     /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
91     /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
92     /// these types in the first place.
93     ///
94     /// The `const` value should be stored inside a `static` item.
95     ///
96     /// ### Known problems
97     /// When an enum has variants with interior mutability, use of its non
98     /// interior mutable variants can generate false positives. See issue
99     /// [#3962](https://github.com/rust-lang/rust-clippy/issues/3962)
100     ///
101     /// Types that have underlying or potential interior mutability trigger the lint whether
102     /// the interior mutable field is used or not. See issues
103     /// [#5812](https://github.com/rust-lang/rust-clippy/issues/5812) and
104     /// [#3825](https://github.com/rust-lang/rust-clippy/issues/3825)
105     ///
106     /// ### Example
107     /// ```rust
108     /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
109     /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
110     ///
111     /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
112     /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
113     /// ```
114     ///
115     /// Use instead:
116     /// ```rust
117     /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
118     /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
119     ///
120     /// static STATIC_ATOM: AtomicUsize = CONST_ATOM;
121     /// STATIC_ATOM.store(9, SeqCst);
122     /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
123     /// ```
124     #[clippy::version = "pre 1.29.0"]
125     pub BORROW_INTERIOR_MUTABLE_CONST,
126     style,
127     "referencing `const` with interior mutability"
128 }
129
130 fn is_unfrozen<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
131     // Ignore types whose layout is unknown since `is_freeze` reports every generic types as `!Freeze`,
132     // making it indistinguishable from `UnsafeCell`. i.e. it isn't a tool to prove a type is
133     // 'unfrozen'. However, this code causes a false negative in which
134     // a type contains a layout-unknown type, but also an unsafe cell like `const CELL: Cell<T>`.
135     // Yet, it's better than `ty.has_type_flags(TypeFlags::HAS_TY_PARAM | TypeFlags::HAS_PROJECTION)`
136     // since it works when a pointer indirection involves (`Cell<*const T>`).
137     // Making up a `ParamEnv` where every generic params and assoc types are `Freeze`is another option;
138     // but I'm not sure whether it's a decent way, if possible.
139     cx.tcx.layout_of(cx.param_env.and(ty)).is_ok() && !ty.is_freeze(cx.tcx, cx.param_env)
140 }
141
142 fn is_value_unfrozen_raw<'tcx>(
143     cx: &LateContext<'tcx>,
144     result: Result<ConstValue<'tcx>, ErrorHandled>,
145     ty: Ty<'tcx>,
146 ) -> bool {
147     fn inner<'tcx>(cx: &LateContext<'tcx>, val: mir::ConstantKind<'tcx>) -> bool {
148         match val.ty().kind() {
149             // the fact that we have to dig into every structs to search enums
150             // leads us to the point checking `UnsafeCell` directly is the only option.
151             ty::Adt(ty_def, ..) if ty_def.is_unsafe_cell() => true,
152             // As of 2022-09-08 miri doesn't track which union field is active so there's no safe way to check the
153             // contained value.
154             ty::Adt(def, ..) if def.is_union() => false,
155             ty::Array(..) | ty::Adt(..) | ty::Tuple(..) => {
156                 let val = cx.tcx.destructure_mir_constant(cx.param_env, val);
157                 val.fields.iter().any(|field| inner(cx, *field))
158             },
159             _ => false,
160         }
161     }
162     result.map_or_else(
163         |err| {
164             // Consider `TooGeneric` cases as being unfrozen.
165             // This causes a false positive where an assoc const whose type is unfrozen
166             // have a value that is a frozen variant with a generic param (an example is
167             // `declare_interior_mutable_const::enums::BothOfCellAndGeneric::GENERIC_VARIANT`).
168             // However, it prevents a number of false negatives that is, I think, important:
169             // 1. assoc consts in trait defs referring to consts of themselves
170             //    (an example is `declare_interior_mutable_const::traits::ConcreteTypes::ANOTHER_ATOMIC`).
171             // 2. a path expr referring to assoc consts whose type is doesn't have
172             //    any frozen variants in trait defs (i.e. without substitute for `Self`).
173             //    (e.g. borrowing `borrow_interior_mutable_const::trait::ConcreteTypes::ATOMIC`)
174             // 3. similar to the false positive above;
175             //    but the value is an unfrozen variant, or the type has no enums. (An example is
176             //    `declare_interior_mutable_const::enums::BothOfCellAndGeneric::UNFROZEN_VARIANT`
177             //    and `declare_interior_mutable_const::enums::BothOfCellAndGeneric::NO_ENUM`).
178             // One might be able to prevent these FNs correctly, and replace this with `false`;
179             // e.g. implementing `has_frozen_variant` described above, and not running this function
180             // when the type doesn't have any frozen variants would be the 'correct' way for the 2nd
181             // case (that actually removes another suboptimal behavior (I won't say 'false positive') where,
182             // similar to 2., but with the a frozen variant) (e.g. borrowing
183             // `borrow_interior_mutable_const::enums::AssocConsts::TO_BE_FROZEN_VARIANT`).
184             // I chose this way because unfrozen enums as assoc consts are rare (or, hopefully, none).
185             err == ErrorHandled::TooGeneric
186         },
187         |val| inner(cx, mir::ConstantKind::from_value(val, ty)),
188     )
189 }
190
191 fn is_value_unfrozen_poly<'tcx>(cx: &LateContext<'tcx>, body_id: BodyId, ty: Ty<'tcx>) -> bool {
192     let result = cx.tcx.const_eval_poly(body_id.hir_id.owner.to_def_id());
193     is_value_unfrozen_raw(cx, result, ty)
194 }
195
196 fn is_value_unfrozen_expr<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId, def_id: DefId, ty: Ty<'tcx>) -> bool {
197     let substs = cx.typeck_results().node_substs(hir_id);
198
199     let result = cx.tcx.const_eval_resolve(
200         cx.param_env,
201         mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs),
202         None,
203     );
204     is_value_unfrozen_raw(cx, result, ty)
205 }
206
207 #[derive(Copy, Clone)]
208 enum Source {
209     Item { item: Span },
210     Assoc { item: Span },
211     Expr { expr: Span },
212 }
213
214 impl Source {
215     #[must_use]
216     fn lint(&self) -> (&'static Lint, &'static str, Span) {
217         match self {
218             Self::Item { item } | Self::Assoc { item, .. } => (
219                 DECLARE_INTERIOR_MUTABLE_CONST,
220                 "a `const` item should never be interior mutable",
221                 *item,
222             ),
223             Self::Expr { expr } => (
224                 BORROW_INTERIOR_MUTABLE_CONST,
225                 "a `const` item with interior mutability should not be borrowed",
226                 *expr,
227             ),
228         }
229     }
230 }
231
232 fn lint(cx: &LateContext<'_>, source: Source) {
233     let (lint, msg, span) = source.lint();
234     span_lint_and_then(cx, lint, span, msg, |diag| {
235         if span.from_expansion() {
236             return; // Don't give suggestions into macros.
237         }
238         match source {
239             Source::Item { .. } => {
240                 let const_kw_span = span.from_inner(InnerSpan::new(0, 5));
241                 diag.span_label(const_kw_span, "make this a static item (maybe with lazy_static)");
242             },
243             Source::Assoc { .. } => (),
244             Source::Expr { .. } => {
245                 diag.help("assign this const to a local or static variable, and use the variable here");
246             },
247         }
248     });
249 }
250
251 declare_lint_pass!(NonCopyConst => [DECLARE_INTERIOR_MUTABLE_CONST, BORROW_INTERIOR_MUTABLE_CONST]);
252
253 impl<'tcx> LateLintPass<'tcx> for NonCopyConst {
254     fn check_item(&mut self, cx: &LateContext<'tcx>, it: &'tcx Item<'_>) {
255         if let ItemKind::Const(hir_ty, body_id) = it.kind {
256             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
257             if !ignored_macro(cx, it) && is_unfrozen(cx, ty) && is_value_unfrozen_poly(cx, body_id, ty) {
258                 lint(cx, Source::Item { item: it.span });
259             }
260         }
261     }
262
263     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, trait_item: &'tcx TraitItem<'_>) {
264         if let TraitItemKind::Const(hir_ty, body_id_opt) = &trait_item.kind {
265             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
266
267             // Normalize assoc types because ones originated from generic params
268             // bounded other traits could have their bound.
269             let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
270             if is_unfrozen(cx, normalized)
271                 // When there's no default value, lint it only according to its type;
272                 // in other words, lint consts whose value *could* be unfrozen, not definitely is.
273                 // This feels inconsistent with how the lint treats generic types,
274                 // which avoids linting types which potentially become unfrozen.
275                 // One could check whether an unfrozen type have a *frozen variant*
276                 // (like `body_id_opt.map_or_else(|| !has_frozen_variant(...), ...)`),
277                 // and do the same as the case of generic types at impl items.
278                 // Note that it isn't sufficient to check if it has an enum
279                 // since all of that enum's variants can be unfrozen:
280                 // i.e. having an enum doesn't necessary mean a type has a frozen variant.
281                 // And, implementing it isn't a trivial task; it'll probably end up
282                 // re-implementing the trait predicate evaluation specific to `Freeze`.
283                 && body_id_opt.map_or(true, |body_id| is_value_unfrozen_poly(cx, body_id, normalized))
284             {
285                 lint(cx, Source::Assoc { item: trait_item.span });
286             }
287         }
288     }
289
290     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx ImplItem<'_>) {
291         if let ImplItemKind::Const(hir_ty, body_id) = &impl_item.kind {
292             let item_def_id = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id;
293             let item = cx.tcx.hir().expect_item(item_def_id);
294
295             match &item.kind {
296                 ItemKind::Impl(Impl {
297                     of_trait: Some(of_trait_ref),
298                     ..
299                 }) => {
300                     if_chain! {
301                         // Lint a trait impl item only when the definition is a generic type,
302                         // assuming an assoc const is not meant to be an interior mutable type.
303                         if let Some(of_trait_def_id) = of_trait_ref.trait_def_id();
304                         if let Some(of_assoc_item) = cx
305                             .tcx
306                             .associated_item(impl_item.owner_id)
307                             .trait_item_def_id;
308                         if cx
309                             .tcx
310                             .layout_of(cx.tcx.param_env(of_trait_def_id).and(
311                                 // Normalize assoc types because ones originated from generic params
312                                 // bounded other traits could have their bound at the trait defs;
313                                 // and, in that case, the definition is *not* generic.
314                                 cx.tcx.normalize_erasing_regions(
315                                     cx.tcx.param_env(of_trait_def_id),
316                                     cx.tcx.type_of(of_assoc_item),
317                                 ),
318                             ))
319                             .is_err();
320                             // If there were a function like `has_frozen_variant` described above,
321                             // we should use here as a frozen variant is a potential to be frozen
322                             // similar to unknown layouts.
323                             // e.g. `layout_of(...).is_err() || has_frozen_variant(...);`
324                         let ty = hir_ty_to_ty(cx.tcx, hir_ty);
325                         let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
326                         if is_unfrozen(cx, normalized);
327                         if is_value_unfrozen_poly(cx, *body_id, normalized);
328                         then {
329                             lint(
330                                cx,
331                                Source::Assoc {
332                                    item: impl_item.span,
333                                 },
334                             );
335                         }
336                     }
337                 },
338                 ItemKind::Impl(Impl { of_trait: None, .. }) => {
339                     let ty = hir_ty_to_ty(cx.tcx, hir_ty);
340                     // Normalize assoc types originated from generic params.
341                     let normalized = cx.tcx.normalize_erasing_regions(cx.param_env, ty);
342
343                     if is_unfrozen(cx, ty) && is_value_unfrozen_poly(cx, *body_id, normalized) {
344                         lint(cx, Source::Assoc { item: impl_item.span });
345                     }
346                 },
347                 _ => (),
348             }
349         }
350     }
351
352     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
353         if let ExprKind::Path(qpath) = &expr.kind {
354             // Only lint if we use the const item inside a function.
355             if in_constant(cx, expr.hir_id) {
356                 return;
357             }
358
359             // Make sure it is a const item.
360             let Res::Def(DefKind::Const | DefKind::AssocConst, item_def_id) = cx.qpath_res(qpath, expr.hir_id) else {
361                 return
362             };
363
364             // Climb up to resolve any field access and explicit referencing.
365             let mut cur_expr = expr;
366             let mut dereferenced_expr = expr;
367             let mut needs_check_adjustment = true;
368             loop {
369                 let parent_id = cx.tcx.hir().get_parent_node(cur_expr.hir_id);
370                 if parent_id == cur_expr.hir_id {
371                     break;
372                 }
373                 if let Some(Node::Expr(parent_expr)) = cx.tcx.hir().find(parent_id) {
374                     match &parent_expr.kind {
375                         ExprKind::AddrOf(..) => {
376                             // `&e` => `e` must be referenced.
377                             needs_check_adjustment = false;
378                         },
379                         ExprKind::Field(..) => {
380                             needs_check_adjustment = true;
381
382                             // Check whether implicit dereferences happened;
383                             // if so, no need to go further up
384                             // because of the same reason as the `ExprKind::Unary` case.
385                             if cx
386                                 .typeck_results()
387                                 .expr_adjustments(dereferenced_expr)
388                                 .iter()
389                                 .any(|adj| matches!(adj.kind, Adjust::Deref(_)))
390                             {
391                                 break;
392                             }
393
394                             dereferenced_expr = parent_expr;
395                         },
396                         ExprKind::Index(e, _) if ptr::eq(&**e, cur_expr) => {
397                             // `e[i]` => desugared to `*Index::index(&e, i)`,
398                             // meaning `e` must be referenced.
399                             // no need to go further up since a method call is involved now.
400                             needs_check_adjustment = false;
401                             break;
402                         },
403                         ExprKind::Unary(UnOp::Deref, _) => {
404                             // `*e` => desugared to `*Deref::deref(&e)`,
405                             // meaning `e` must be referenced.
406                             // no need to go further up since a method call is involved now.
407                             needs_check_adjustment = false;
408                             break;
409                         },
410                         _ => break,
411                     }
412                     cur_expr = parent_expr;
413                 } else {
414                     break;
415                 }
416             }
417
418             let ty = if needs_check_adjustment {
419                 let adjustments = cx.typeck_results().expr_adjustments(dereferenced_expr);
420                 if let Some(i) = adjustments
421                     .iter()
422                     .position(|adj| matches!(adj.kind, Adjust::Borrow(_) | Adjust::Deref(_)))
423                 {
424                     if i == 0 {
425                         cx.typeck_results().expr_ty(dereferenced_expr)
426                     } else {
427                         adjustments[i - 1].target
428                     }
429                 } else {
430                     // No borrow adjustments means the entire const is moved.
431                     return;
432                 }
433             } else {
434                 cx.typeck_results().expr_ty(dereferenced_expr)
435             };
436
437             if is_unfrozen(cx, ty) && is_value_unfrozen_expr(cx, expr.hir_id, item_def_id, ty) {
438                 lint(cx, Source::Expr { expr: expr.span });
439             }
440         }
441     }
442 }
443
444 fn ignored_macro(cx: &LateContext<'_>, it: &rustc_hir::Item<'_>) -> bool {
445     macro_backtrace(it.span).any(|macro_call| {
446         matches!(
447             cx.tcx.get_diagnostic_name(macro_call.def_id),
448             Some(sym::thread_local_macro)
449         )
450     })
451 }