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