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