]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/mem_replace.rs
Special sync of 'e89801553ddbaccdeb2eac4db08900edb51ac7ff'
[rust.git] / src / tools / clippy / clippy_lints / src / mem_replace.rs
1 use crate::utils::{
2     in_macro, match_def_path, match_qpath, meets_msrv, paths, snippet, snippet_with_applicability, span_lint_and_help,
3     span_lint_and_sugg, span_lint_and_then,
4 };
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, QPath};
8 use rustc_lint::{LateContext, LateLintPass, LintContext};
9 use rustc_middle::lint::in_external_macro;
10 use rustc_semver::RustcVersion;
11 use rustc_session::{declare_tool_lint, impl_lint_pass};
12 use rustc_span::source_map::Span;
13 use rustc_span::symbol::sym;
14
15 declare_clippy_lint! {
16     /// **What it does:** Checks for `mem::replace()` on an `Option` with
17     /// `None`.
18     ///
19     /// **Why is this bad?** `Option` already has the method `take()` for
20     /// taking its current value (Some(..) or None) and replacing it with
21     /// `None`.
22     ///
23     /// **Known problems:** None.
24     ///
25     /// **Example:**
26     /// ```rust
27     /// use std::mem;
28     ///
29     /// let mut an_option = Some(0);
30     /// let replaced = mem::replace(&mut an_option, None);
31     /// ```
32     /// Is better expressed with:
33     /// ```rust
34     /// let mut an_option = Some(0);
35     /// let taken = an_option.take();
36     /// ```
37     pub MEM_REPLACE_OPTION_WITH_NONE,
38     style,
39     "replacing an `Option` with `None` instead of `take()`"
40 }
41
42 declare_clippy_lint! {
43     /// **What it does:** Checks for `mem::replace(&mut _, mem::uninitialized())`
44     /// and `mem::replace(&mut _, mem::zeroed())`.
45     ///
46     /// **Why is this bad?** This will lead to undefined behavior even if the
47     /// value is overwritten later, because the uninitialized value may be
48     /// observed in the case of a panic.
49     ///
50     /// **Known problems:** None.
51     ///
52     /// **Example:**
53     ///
54     /// ```
55     /// use std::mem;
56     ///# fn may_panic(v: Vec<i32>) -> Vec<i32> { v }
57     ///
58     /// #[allow(deprecated, invalid_value)]
59     /// fn myfunc (v: &mut Vec<i32>) {
60     ///     let taken_v = unsafe { mem::replace(v, mem::uninitialized()) };
61     ///     let new_v = may_panic(taken_v); // undefined behavior on panic
62     ///     mem::forget(mem::replace(v, new_v));
63     /// }
64     /// ```
65     ///
66     /// The [take_mut](https://docs.rs/take_mut) crate offers a sound solution,
67     /// at the cost of either lazily creating a replacement value or aborting
68     /// on panic, to ensure that the uninitialized value cannot be observed.
69     pub MEM_REPLACE_WITH_UNINIT,
70     correctness,
71     "`mem::replace(&mut _, mem::uninitialized())` or `mem::replace(&mut _, mem::zeroed())`"
72 }
73
74 declare_clippy_lint! {
75     /// **What it does:** Checks for `std::mem::replace` on a value of type
76     /// `T` with `T::default()`.
77     ///
78     /// **Why is this bad?** `std::mem` module already has the method `take` to
79     /// take the current value and replace it with the default value of that type.
80     ///
81     /// **Known problems:** None.
82     ///
83     /// **Example:**
84     /// ```rust
85     /// let mut text = String::from("foo");
86     /// let replaced = std::mem::replace(&mut text, String::default());
87     /// ```
88     /// Is better expressed with:
89     /// ```rust
90     /// let mut text = String::from("foo");
91     /// let taken = std::mem::take(&mut text);
92     /// ```
93     pub MEM_REPLACE_WITH_DEFAULT,
94     style,
95     "replacing a value of type `T` with `T::default()` instead of using `std::mem::take`"
96 }
97
98 impl_lint_pass!(MemReplace =>
99     [MEM_REPLACE_OPTION_WITH_NONE, MEM_REPLACE_WITH_UNINIT, MEM_REPLACE_WITH_DEFAULT]);
100
101 fn check_replace_option_with_none(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
102     if let ExprKind::Path(ref replacement_qpath) = src.kind {
103         // Check that second argument is `Option::None`
104         if match_qpath(replacement_qpath, &paths::OPTION_NONE) {
105             // Since this is a late pass (already type-checked),
106             // and we already know that the second argument is an
107             // `Option`, we do not need to check the first
108             // argument's type. All that's left is to get
109             // replacee's path.
110             let replaced_path = match dest.kind {
111                 ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, ref replaced) => {
112                     if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.kind {
113                         replaced_path
114                     } else {
115                         return;
116                     }
117                 },
118                 ExprKind::Path(QPath::Resolved(None, ref replaced_path)) => replaced_path,
119                 _ => return,
120             };
121
122             let mut applicability = Applicability::MachineApplicable;
123             span_lint_and_sugg(
124                 cx,
125                 MEM_REPLACE_OPTION_WITH_NONE,
126                 expr_span,
127                 "replacing an `Option` with `None`",
128                 "consider `Option::take()` instead",
129                 format!(
130                     "{}.take()",
131                     snippet_with_applicability(cx, replaced_path.span, "", &mut applicability)
132                 ),
133                 applicability,
134             );
135         }
136     }
137 }
138
139 fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
140     if_chain! {
141         // check if replacement is mem::MaybeUninit::uninit().assume_init()
142         if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(src.hir_id);
143         if cx.tcx.is_diagnostic_item(sym::assume_init, method_def_id);
144         then {
145             let mut applicability = Applicability::MachineApplicable;
146             span_lint_and_sugg(
147                 cx,
148                 MEM_REPLACE_WITH_UNINIT,
149                 expr_span,
150                 "replacing with `mem::MaybeUninit::uninit().assume_init()`",
151                 "consider using",
152                 format!(
153                     "std::ptr::read({})",
154                     snippet_with_applicability(cx, dest.span, "", &mut applicability)
155                 ),
156                 applicability,
157             );
158             return;
159         }
160     }
161
162     if_chain! {
163         if let ExprKind::Call(ref repl_func, ref repl_args) = src.kind;
164         if repl_args.is_empty();
165         if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind;
166         if let Some(repl_def_id) = cx.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id();
167         then {
168             if cx.tcx.is_diagnostic_item(sym::mem_uninitialized, repl_def_id) {
169                 let mut applicability = Applicability::MachineApplicable;
170                 span_lint_and_sugg(
171                     cx,
172                     MEM_REPLACE_WITH_UNINIT,
173                     expr_span,
174                     "replacing with `mem::uninitialized()`",
175                     "consider using",
176                     format!(
177                         "std::ptr::read({})",
178                         snippet_with_applicability(cx, dest.span, "", &mut applicability)
179                     ),
180                     applicability,
181                 );
182             } else if cx.tcx.is_diagnostic_item(sym::mem_zeroed, repl_def_id) &&
183                     !cx.typeck_results().expr_ty(src).is_primitive() {
184                 span_lint_and_help(
185                     cx,
186                     MEM_REPLACE_WITH_UNINIT,
187                     expr_span,
188                     "replacing with `mem::zeroed()`",
189                     None,
190                     "consider using a default value or the `take_mut` crate instead",
191                 );
192             }
193         }
194     }
195 }
196
197 fn check_replace_with_default(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
198     if let ExprKind::Call(ref repl_func, _) = src.kind {
199         if_chain! {
200             if !in_external_macro(cx.tcx.sess, expr_span);
201             if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind;
202             if let Some(repl_def_id) = cx.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id();
203             if match_def_path(cx, repl_def_id, &paths::DEFAULT_TRAIT_METHOD);
204             then {
205                 span_lint_and_then(
206                     cx,
207                     MEM_REPLACE_WITH_DEFAULT,
208                     expr_span,
209                     "replacing a value of type `T` with `T::default()` is better expressed using `std::mem::take`",
210                     |diag| {
211                         if !in_macro(expr_span) {
212                             let suggestion = format!("std::mem::take({})", snippet(cx, dest.span, ""));
213
214                             diag.span_suggestion(
215                                 expr_span,
216                                 "consider using",
217                                 suggestion,
218                                 Applicability::MachineApplicable
219                             );
220                         }
221                     }
222                 );
223             }
224         }
225     }
226 }
227
228 const MEM_REPLACE_WITH_DEFAULT_MSRV: RustcVersion = RustcVersion::new(1, 40, 0);
229
230 pub struct MemReplace {
231     msrv: Option<RustcVersion>,
232 }
233
234 impl MemReplace {
235     #[must_use]
236     pub fn new(msrv: Option<RustcVersion>) -> Self {
237         Self { msrv }
238     }
239 }
240
241 impl<'tcx> LateLintPass<'tcx> for MemReplace {
242     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
243         if_chain! {
244             // Check that `expr` is a call to `mem::replace()`
245             if let ExprKind::Call(ref func, ref func_args) = expr.kind;
246             if let ExprKind::Path(ref func_qpath) = func.kind;
247             if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id();
248             if match_def_path(cx, def_id, &paths::MEM_REPLACE);
249             if let [dest, src] = &**func_args;
250             then {
251                 check_replace_option_with_none(cx, src, dest, expr.span);
252                 check_replace_with_uninit(cx, src, dest, expr.span);
253                 if meets_msrv(self.msrv.as_ref(), &MEM_REPLACE_WITH_DEFAULT_MSRV) {
254                     check_replace_with_default(cx, src, dest, expr.span);
255                 }
256             }
257         }
258     }
259     extract_msrv_attr!(LateContext);
260 }