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