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