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