]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/non_copy_const.rs
Auto merge of #5242 - matthiaskrgr:5238_test, r=flip1995
[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::ty::adjustment::Adjust;
8 use rustc::ty::{Ty, TypeFlags};
9 use rustc_hir::def::{DefKind, Res};
10 use rustc_hir::{Expr, ExprKind, ImplItem, ImplItemKind, Item, ItemKind, Node, TraitItem, TraitItemKind, UnOp};
11 use rustc_lint::{LateContext, LateLintPass, Lint};
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::{InnerSpan, Span, DUMMY_SP};
14 use rustc_typeck::hir_ty_to_ty;
15
16 use crate::utils::{in_constant, is_copy, qpath_res, span_lint_and_then};
17
18 declare_clippy_lint! {
19     /// **What it does:** Checks for declaration of `const` items which is interior
20     /// mutable (e.g., contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.).
21     ///
22     /// **Why is this bad?** Consts are copied everywhere they are referenced, i.e.,
23     /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
24     /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
25     /// these types in the first place.
26     ///
27     /// The `const` should better be replaced by a `static` item if a global
28     /// variable is wanted, or replaced by a `const fn` if a constructor is wanted.
29     ///
30     /// **Known problems:** A "non-constant" const item is a legacy way to supply an
31     /// initialized value to downstream `static` items (e.g., the
32     /// `std::sync::ONCE_INIT` constant). In this case the use of `const` is legit,
33     /// and this lint should be suppressed.
34     ///
35     /// **Example:**
36     /// ```rust
37     /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
38     ///
39     /// // Bad.
40     /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
41     /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
42     /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
43     ///
44     /// // Good.
45     /// static STATIC_ATOM: AtomicUsize = AtomicUsize::new(15);
46     /// STATIC_ATOM.store(9, SeqCst);
47     /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
48     /// ```
49     pub DECLARE_INTERIOR_MUTABLE_CONST,
50     correctness,
51     "declaring `const` with interior mutability"
52 }
53
54 declare_clippy_lint! {
55     /// **What it does:** Checks if `const` items which is interior mutable (e.g.,
56     /// contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.) has been borrowed directly.
57     ///
58     /// **Why is this bad?** Consts are copied everywhere they are referenced, i.e.,
59     /// every time you refer to the const a fresh instance of the `Cell` or `Mutex`
60     /// or `AtomicXxxx` will be created, which defeats the whole purpose of using
61     /// these types in the first place.
62     ///
63     /// The `const` value should be stored inside a `static` item.
64     ///
65     /// **Known problems:** None
66     ///
67     /// **Example:**
68     /// ```rust
69     /// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
70     /// const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
71     ///
72     /// // Bad.
73     /// CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
74     /// assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
75     ///
76     /// // Good.
77     /// static STATIC_ATOM: AtomicUsize = CONST_ATOM;
78     /// STATIC_ATOM.store(9, SeqCst);
79     /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
80     /// ```
81     pub BORROW_INTERIOR_MUTABLE_CONST,
82     correctness,
83     "referencing `const` with interior mutability"
84 }
85
86 #[allow(dead_code)]
87 #[derive(Copy, Clone)]
88 enum Source {
89     Item { item: Span },
90     Assoc { item: Span, ty: Span },
91     Expr { expr: Span },
92 }
93
94 impl Source {
95     #[must_use]
96     fn lint(&self) -> (&'static Lint, &'static str, Span) {
97         match self {
98             Self::Item { item } | Self::Assoc { item, .. } => (
99                 DECLARE_INTERIOR_MUTABLE_CONST,
100                 "a `const` item should never be interior mutable",
101                 *item,
102             ),
103             Self::Expr { expr } => (
104                 BORROW_INTERIOR_MUTABLE_CONST,
105                 "a `const` item with interior mutability should not be borrowed",
106                 *expr,
107             ),
108         }
109     }
110 }
111
112 fn verify_ty_bound<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>, source: Source) {
113     if ty.is_freeze(cx.tcx, cx.param_env, DUMMY_SP) || is_copy(cx, ty) {
114         // An `UnsafeCell` is `!Copy`, and an `UnsafeCell` is also the only type which
115         // is `!Freeze`, thus if our type is `Copy` we can be sure it must be `Freeze`
116         // as well.
117         return;
118     }
119
120     let (lint, msg, span) = source.lint();
121     span_lint_and_then(cx, lint, span, msg, |db| {
122         if span.from_expansion() {
123             return; // Don't give suggestions into macros.
124         }
125         match source {
126             Source::Item { .. } => {
127                 let const_kw_span = span.from_inner(InnerSpan::new(0, 5));
128                 db.span_label(const_kw_span, "make this a static item (maybe with lazy_static)");
129             },
130             Source::Assoc { ty: ty_span, .. } => {
131                 if ty.flags.intersects(TypeFlags::HAS_FREE_LOCAL_NAMES) {
132                     db.span_label(ty_span, &format!("consider requiring `{}` to be `Copy`", ty));
133                 }
134             },
135             Source::Expr { .. } => {
136                 db.help("assign this const to a local or static variable, and use the variable here");
137             },
138         }
139     });
140 }
141
142 declare_lint_pass!(NonCopyConst => [DECLARE_INTERIOR_MUTABLE_CONST, BORROW_INTERIOR_MUTABLE_CONST]);
143
144 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCopyConst {
145     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, it: &'tcx Item<'_>) {
146         if let ItemKind::Const(hir_ty, ..) = &it.kind {
147             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
148             verify_ty_bound(cx, ty, Source::Item { item: it.span });
149         }
150     }
151
152     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, trait_item: &'tcx TraitItem<'_>) {
153         if let TraitItemKind::Const(hir_ty, ..) = &trait_item.kind {
154             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
155             verify_ty_bound(
156                 cx,
157                 ty,
158                 Source::Assoc {
159                     ty: hir_ty.span,
160                     item: trait_item.span,
161                 },
162             );
163         }
164     }
165
166     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, impl_item: &'tcx ImplItem<'_>) {
167         if let ImplItemKind::Const(hir_ty, ..) = &impl_item.kind {
168             let item_hir_id = cx.tcx.hir().get_parent_node(impl_item.hir_id);
169             let item = cx.tcx.hir().expect_item(item_hir_id);
170             // Ensure the impl is an inherent impl.
171             if let ItemKind::Impl { of_trait: None, .. } = item.kind {
172                 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
173                 verify_ty_bound(
174                     cx,
175                     ty,
176                     Source::Assoc {
177                         ty: hir_ty.span,
178                         item: impl_item.span,
179                     },
180                 );
181             }
182         }
183     }
184
185     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
186         if let ExprKind::Path(qpath) = &expr.kind {
187             // Only lint if we use the const item inside a function.
188             if in_constant(cx, expr.hir_id) {
189                 return;
190             }
191
192             // Make sure it is a const item.
193             match qpath_res(cx, qpath, expr.hir_id) {
194                 Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) => {},
195                 _ => return,
196             };
197
198             // Climb up to resolve any field access and explicit referencing.
199             let mut cur_expr = expr;
200             let mut dereferenced_expr = expr;
201             let mut needs_check_adjustment = true;
202             loop {
203                 let parent_id = cx.tcx.hir().get_parent_node(cur_expr.hir_id);
204                 if parent_id == cur_expr.hir_id {
205                     break;
206                 }
207                 if let Some(Node::Expr(parent_expr)) = cx.tcx.hir().find(parent_id) {
208                     match &parent_expr.kind {
209                         ExprKind::AddrOf(..) => {
210                             // `&e` => `e` must be referenced.
211                             needs_check_adjustment = false;
212                         },
213                         ExprKind::Field(..) => {
214                             dereferenced_expr = parent_expr;
215                             needs_check_adjustment = true;
216                         },
217                         ExprKind::Index(e, _) if ptr::eq(&**e, cur_expr) => {
218                             // `e[i]` => desugared to `*Index::index(&e, i)`,
219                             // meaning `e` must be referenced.
220                             // no need to go further up since a method call is involved now.
221                             needs_check_adjustment = false;
222                             break;
223                         },
224                         ExprKind::Unary(UnOp::UnDeref, _) => {
225                             // `*e` => desugared to `*Deref::deref(&e)`,
226                             // meaning `e` must be referenced.
227                             // no need to go further up since a method call is involved now.
228                             needs_check_adjustment = false;
229                             break;
230                         },
231                         _ => break,
232                     }
233                     cur_expr = parent_expr;
234                 } else {
235                     break;
236                 }
237             }
238
239             let ty = if needs_check_adjustment {
240                 let adjustments = cx.tables.expr_adjustments(dereferenced_expr);
241                 if let Some(i) = adjustments.iter().position(|adj| match adj.kind {
242                     Adjust::Borrow(_) | Adjust::Deref(_) => true,
243                     _ => false,
244                 }) {
245                     if i == 0 {
246                         cx.tables.expr_ty(dereferenced_expr)
247                     } else {
248                         adjustments[i - 1].target
249                     }
250                 } else {
251                     // No borrow adjustments means the entire const is moved.
252                     return;
253                 }
254             } else {
255                 cx.tables.expr_ty(dereferenced_expr)
256             };
257
258             verify_ty_bound(cx, ty, Source::Expr { expr: expr.span });
259         }
260     }
261 }