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