]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/mem_replace.rs
Auto merge of #7067 - TaKO8Ki:fix-false-negative-on-needless-return, r=llogiq
[rust.git] / 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::{in_macro, match_def_path, meets_msrv, paths};
4 use clippy_utils::{is_diagnostic_assoc_item, is_lang_ctor};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::def_id::DefId;
8 use rustc_hir::LangItem::OptionNone;
9 use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, QPath};
10 use rustc_lint::{LateContext, LateLintPass, LintContext};
11 use rustc_middle::lint::in_external_macro;
12 use rustc_semver::RustcVersion;
13 use rustc_session::{declare_tool_lint, impl_lint_pass};
14 use rustc_span::source_map::Span;
15 use rustc_span::symbol::sym;
16
17 declare_clippy_lint! {
18     /// **What it does:** Checks for `mem::replace()` on an `Option` with
19     /// `None`.
20     ///
21     /// **Why is this bad?** `Option` already has the method `take()` for
22     /// taking its current value (Some(..) or None) and replacing it with
23     /// `None`.
24     ///
25     /// **Known problems:** None.
26     ///
27     /// **Example:**
28     /// ```rust
29     /// use std::mem;
30     ///
31     /// let mut an_option = Some(0);
32     /// let replaced = mem::replace(&mut an_option, None);
33     /// ```
34     /// Is better expressed with:
35     /// ```rust
36     /// let mut an_option = Some(0);
37     /// let taken = an_option.take();
38     /// ```
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:** Checks for `mem::replace(&mut _, mem::uninitialized())`
46     /// and `mem::replace(&mut _, mem::zeroed())`.
47     ///
48     /// **Why is this bad?** This will lead to undefined behavior even if the
49     /// value is overwritten later, because the uninitialized value may be
50     /// observed in the case of a panic.
51     ///
52     /// **Known problems:** None.
53     ///
54     /// **Example:**
55     ///
56     /// ```
57     /// use std::mem;
58     ///# fn may_panic(v: Vec<i32>) -> Vec<i32> { v }
59     ///
60     /// #[allow(deprecated, invalid_value)]
61     /// fn myfunc (v: &mut Vec<i32>) {
62     ///     let taken_v = unsafe { mem::replace(v, mem::uninitialized()) };
63     ///     let new_v = may_panic(taken_v); // undefined behavior on panic
64     ///     mem::forget(mem::replace(v, new_v));
65     /// }
66     /// ```
67     ///
68     /// The [take_mut](https://docs.rs/take_mut) crate offers a sound solution,
69     /// at the cost of either lazily creating a replacement value or aborting
70     /// on panic, to ensure that the uninitialized value cannot be observed.
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:** Checks for `std::mem::replace` on a value of type
78     /// `T` with `T::default()`.
79     ///
80     /// **Why is this bad?** `std::mem` module already has the method `take` to
81     /// take the current value and replace it with the default value of that type.
82     ///
83     /// **Known problems:** None.
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     pub MEM_REPLACE_WITH_DEFAULT,
96     style,
97     "replacing a value of type `T` with `T::default()` instead of using `std::mem::take`"
98 }
99
100 impl_lint_pass!(MemReplace =>
101     [MEM_REPLACE_OPTION_WITH_NONE, MEM_REPLACE_WITH_UNINIT, MEM_REPLACE_WITH_DEFAULT]);
102
103 fn check_replace_option_with_none(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
104     if let ExprKind::Path(ref replacement_qpath) = src.kind {
105         // Check that second argument is `Option::None`
106         if is_lang_ctor(cx, replacement_qpath, 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
141 fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
142     if_chain! {
143         // check if replacement is mem::MaybeUninit::uninit().assume_init()
144         if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(src.hir_id);
145         if cx.tcx.is_diagnostic_item(sym::assume_init, method_def_id);
146         then {
147             let mut applicability = Applicability::MachineApplicable;
148             span_lint_and_sugg(
149                 cx,
150                 MEM_REPLACE_WITH_UNINIT,
151                 expr_span,
152                 "replacing with `mem::MaybeUninit::uninit().assume_init()`",
153                 "consider using",
154                 format!(
155                     "std::ptr::read({})",
156                     snippet_with_applicability(cx, dest.span, "", &mut applicability)
157                 ),
158                 applicability,
159             );
160             return;
161         }
162     }
163
164     if_chain! {
165         if let ExprKind::Call(repl_func, repl_args) = src.kind;
166         if repl_args.is_empty();
167         if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind;
168         if let Some(repl_def_id) = cx.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id();
169         then {
170             if cx.tcx.is_diagnostic_item(sym::mem_uninitialized, repl_def_id) {
171                 let mut applicability = Applicability::MachineApplicable;
172                 span_lint_and_sugg(
173                     cx,
174                     MEM_REPLACE_WITH_UNINIT,
175                     expr_span,
176                     "replacing with `mem::uninitialized()`",
177                     "consider using",
178                     format!(
179                         "std::ptr::read({})",
180                         snippet_with_applicability(cx, dest.span, "", &mut applicability)
181                     ),
182                     applicability,
183                 );
184             } else if cx.tcx.is_diagnostic_item(sym::mem_zeroed, repl_def_id) &&
185                     !cx.typeck_results().expr_ty(src).is_primitive() {
186                 span_lint_and_help(
187                     cx,
188                     MEM_REPLACE_WITH_UNINIT,
189                     expr_span,
190                     "replacing with `mem::zeroed()`",
191                     None,
192                     "consider using a default value or the `take_mut` crate instead",
193                 );
194             }
195         }
196     }
197 }
198
199 /// Returns true if the `def_id` associated with the `path` is recognized as a "default-equivalent"
200 /// constructor from the std library
201 fn is_default_equivalent_ctor(cx: &LateContext<'_>, def_id: DefId, path: &QPath<'_>) -> bool {
202     let std_types_symbols = &[
203         sym::string_type,
204         sym::vec_type,
205         sym::vecdeque_type,
206         sym::LinkedList,
207         sym::hashmap_type,
208         sym::BTreeMap,
209         sym::hashset_type,
210         sym::BTreeSet,
211         sym::BinaryHeap,
212     ];
213
214     if std_types_symbols
215         .iter()
216         .any(|symbol| is_diagnostic_assoc_item(cx, def_id, *symbol))
217     {
218         if let QPath::TypeRelative(_, method) = path {
219             if method.ident.name == sym::new {
220                 return true;
221             }
222         }
223     }
224
225     false
226 }
227
228 fn check_replace_with_default(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
229     if_chain! {
230         if let ExprKind::Call(repl_func, _) = src.kind;
231         if !in_external_macro(cx.tcx.sess, expr_span);
232         if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind;
233         if let Some(repl_def_id) = cx.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id();
234         if is_diagnostic_assoc_item(cx, repl_def_id, sym::Default)
235             || is_default_equivalent_ctor(cx, repl_def_id, repl_func_qpath);
236
237         then {
238             span_lint_and_then(
239                 cx,
240                 MEM_REPLACE_WITH_DEFAULT,
241                 expr_span,
242                 "replacing a value of type `T` with `T::default()` is better expressed using `std::mem::take`",
243                 |diag| {
244                     if !in_macro(expr_span) {
245                         let suggestion = format!("std::mem::take({})", snippet(cx, dest.span, ""));
246
247                         diag.span_suggestion(
248                             expr_span,
249                             "consider using",
250                             suggestion,
251                             Applicability::MachineApplicable
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(func, 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 }