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