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