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