]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/mem_replace.rs
Auto merge of #102332 - chriswailes:ndk-update, r=chriswailes
[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::source::{snippet, snippet_with_applicability};
3 use clippy_utils::ty::is_non_aggregate_primitive_type;
4 use clippy_utils::{is_default_equivalent, is_res_lang_ctor, meets_msrv, msrvs, path_res};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::LangItem::OptionNone;
8 use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, QPath};
9 use rustc_lint::{LateContext, LateLintPass};
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
18     /// Checks for `mem::replace()` on an `Option` with
19     /// `None`.
20     ///
21     /// ### Why is this bad?
22     /// `Option` already has the method `take()` for
23     /// taking its current value (Some(..) or None) and replacing it with
24     /// `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     #[clippy::version = "1.31.0"]
39     pub MEM_REPLACE_OPTION_WITH_NONE,
40     style,
41     "replacing an `Option` with `None` instead of `take()`"
42 }
43
44 declare_clippy_lint! {
45     /// ### What it does
46     /// Checks for `mem::replace(&mut _, mem::uninitialized())`
47     /// and `mem::replace(&mut _, mem::zeroed())`.
48     ///
49     /// ### Why is this bad?
50     /// This will lead to undefined behavior even if the
51     /// value is overwritten later, because the uninitialized value may be
52     /// observed in the case of a panic.
53     ///
54     /// ### Example
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     #[clippy::version = "1.39.0"]
71     pub MEM_REPLACE_WITH_UNINIT,
72     correctness,
73     "`mem::replace(&mut _, mem::uninitialized())` or `mem::replace(&mut _, mem::zeroed())`"
74 }
75
76 declare_clippy_lint! {
77     /// ### What it does
78     /// Checks for `std::mem::replace` on a value of type
79     /// `T` with `T::default()`.
80     ///
81     /// ### Why is this bad?
82     /// `std::mem` module already has the method `take` to
83     /// take the current value and replace it with the default value of that type.
84     ///
85     /// ### Example
86     /// ```rust
87     /// let mut text = String::from("foo");
88     /// let replaced = std::mem::replace(&mut text, String::default());
89     /// ```
90     /// Is better expressed with:
91     /// ```rust
92     /// let mut text = String::from("foo");
93     /// let taken = std::mem::take(&mut text);
94     /// ```
95     #[clippy::version = "1.42.0"]
96     pub MEM_REPLACE_WITH_DEFAULT,
97     style,
98     "replacing a value of type `T` with `T::default()` instead of using `std::mem::take`"
99 }
100
101 impl_lint_pass!(MemReplace =>
102     [MEM_REPLACE_OPTION_WITH_NONE, MEM_REPLACE_WITH_UNINIT, MEM_REPLACE_WITH_DEFAULT]);
103
104 fn check_replace_option_with_none(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
105     // Check that second argument is `Option::None`
106     if is_res_lang_ctor(cx, path_res(cx, src), OptionNone) {
107         // Since this is a late pass (already type-checked),
108         // and we already know that the second argument is an
109         // `Option`, we do not need to check the first
110         // argument's type. All that's left is to get
111         // replacee's path.
112         let replaced_path = match dest.kind {
113             ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, replaced) => {
114                 if let ExprKind::Path(QPath::Resolved(None, replaced_path)) = replaced.kind {
115                     replaced_path
116                 } else {
117                     return;
118                 }
119             },
120             ExprKind::Path(QPath::Resolved(None, replaced_path)) => replaced_path,
121             _ => return,
122         };
123
124         let mut applicability = Applicability::MachineApplicable;
125         span_lint_and_sugg(
126             cx,
127             MEM_REPLACE_OPTION_WITH_NONE,
128             expr_span,
129             "replacing an `Option` with `None`",
130             "consider `Option::take()` instead",
131             format!(
132                 "{}.take()",
133                 snippet_with_applicability(cx, replaced_path.span, "", &mut applicability)
134             ),
135             applicability,
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(repl_func, []) = src.kind;
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     // disable lint for primitives
199     let expr_type = cx.typeck_results().expr_ty_adjusted(src);
200     if is_non_aggregate_primitive_type(expr_type) {
201         return;
202     }
203     // disable lint for Option since it is covered in another lint
204     if is_res_lang_ctor(cx, path_res(cx, src), OptionNone) {
205         return;
206     }
207     if is_default_equivalent(cx, src) && !in_external_macro(cx.tcx.sess, expr_span) {
208         span_lint_and_then(
209             cx,
210             MEM_REPLACE_WITH_DEFAULT,
211             expr_span,
212             "replacing a value of type `T` with `T::default()` is better expressed using `std::mem::take`",
213             |diag| {
214                 if !expr_span.from_expansion() {
215                     let suggestion = format!("std::mem::take({})", snippet(cx, dest.span, ""));
216
217                     diag.span_suggestion(
218                         expr_span,
219                         "consider using",
220                         suggestion,
221                         Applicability::MachineApplicable,
222                     );
223                 }
224             },
225         );
226     }
227 }
228
229 pub struct MemReplace {
230     msrv: Option<RustcVersion>,
231 }
232
233 impl MemReplace {
234     #[must_use]
235     pub fn new(msrv: Option<RustcVersion>) -> Self {
236         Self { msrv }
237     }
238 }
239
240 impl<'tcx> LateLintPass<'tcx> for MemReplace {
241     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
242         if_chain! {
243             // Check that `expr` is a call to `mem::replace()`
244             if let ExprKind::Call(func, [dest, src]) = expr.kind;
245             if let ExprKind::Path(ref func_qpath) = func.kind;
246             if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id();
247             if cx.tcx.is_diagnostic_item(sym::mem_replace, def_id);
248             then {
249                 check_replace_option_with_none(cx, src, dest, expr.span);
250                 check_replace_with_uninit(cx, src, dest, expr.span);
251                 if meets_msrv(self.msrv, msrvs::MEM_TAKE) {
252                     check_replace_with_default(cx, src, dest, expr.span);
253                 }
254             }
255         }
256     }
257     extract_msrv_attr!(LateContext);
258 }