]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/mem_replace.rs
Rustup to rust-lang/rust#66878
[rust.git] / clippy_lints / src / mem_replace.rs
1 use crate::utils::{
2     match_def_path, match_qpath, paths, snippet_with_applicability, span_help_and_lint, span_lint_and_sugg,
3 };
4 use if_chain::if_chain;
5 use rustc::declare_lint_pass;
6 use rustc::hir::{BorrowKind, Expr, ExprKind, Mutability, QPath};
7 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
8 use rustc_errors::Applicability;
9 use rustc_session::declare_tool_lint;
10
11 declare_clippy_lint! {
12     /// **What it does:** Checks for `mem::replace()` on an `Option` with
13     /// `None`.
14     ///
15     /// **Why is this bad?** `Option` already has the method `take()` for
16     /// taking its current value (Some(..) or None) and replacing it with
17     /// `None`.
18     ///
19     /// **Known problems:** None.
20     ///
21     /// **Example:**
22     /// ```rust
23     /// use std::mem;
24     ///
25     /// let mut an_option = Some(0);
26     /// let replaced = mem::replace(&mut an_option, None);
27     /// ```
28     /// Is better expressed with:
29     /// ```rust
30     /// let mut an_option = Some(0);
31     /// let taken = an_option.take();
32     /// ```
33     pub MEM_REPLACE_OPTION_WITH_NONE,
34     style,
35     "replacing an `Option` with `None` instead of `take()`"
36 }
37
38 declare_clippy_lint! {
39     /// **What it does:** Checks for `mem::replace(&mut _, mem::uninitialized())`
40     /// and `mem::replace(&mut _, mem::zeroed())`.
41     ///
42     /// **Why is this bad?** This will lead to undefined behavior even if the
43     /// value is overwritten later, because the uninitialized value may be
44     /// observed in the case of a panic.
45     ///
46     /// **Known problems:** None.
47     ///
48     /// **Example:**
49     ///
50     /// ```
51     /// use std::mem;
52     ///# fn may_panic(v: Vec<i32>) -> Vec<i32> { v }
53     ///
54     /// #[allow(deprecated, invalid_value)]
55     /// fn myfunc (v: &mut Vec<i32>) {
56     ///     let taken_v = unsafe { mem::replace(v, mem::uninitialized()) };
57     ///     let new_v = may_panic(taken_v); // undefined behavior on panic
58     ///     mem::forget(mem::replace(v, new_v));
59     /// }
60     /// ```
61     ///
62     /// The [take_mut](https://docs.rs/take_mut) crate offers a sound solution,
63     /// at the cost of either lazily creating a replacement value or aborting
64     /// on panic, to ensure that the uninitialized value cannot be observed.
65     pub MEM_REPLACE_WITH_UNINIT,
66     correctness,
67     "`mem::replace(&mut _, mem::uninitialized())` or `mem::replace(&mut _, mem::zeroed())`"
68 }
69
70 declare_lint_pass!(MemReplace =>
71     [MEM_REPLACE_OPTION_WITH_NONE, MEM_REPLACE_WITH_UNINIT]);
72
73 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemReplace {
74     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
75         if_chain! {
76             // Check that `expr` is a call to `mem::replace()`
77             if let ExprKind::Call(ref func, ref func_args) = expr.kind;
78             if func_args.len() == 2;
79             if let ExprKind::Path(ref func_qpath) = func.kind;
80             if let Some(def_id) = cx.tables.qpath_res(func_qpath, func.hir_id).opt_def_id();
81             if match_def_path(cx, def_id, &paths::MEM_REPLACE);
82
83             // Check that second argument is `Option::None`
84             then {
85                 if let ExprKind::Path(ref replacement_qpath) = func_args[1].kind {
86                     if match_qpath(replacement_qpath, &paths::OPTION_NONE) {
87
88                         // Since this is a late pass (already type-checked),
89                         // and we already know that the second argument is an
90                         // `Option`, we do not need to check the first
91                         // argument's type. All that's left is to get
92                         // replacee's path.
93                         let replaced_path = match func_args[0].kind {
94                             ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mutable, ref replaced) => {
95                                 if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.kind {
96                                     replaced_path
97                                 } else {
98                                     return
99                                 }
100                             },
101                             ExprKind::Path(QPath::Resolved(None, ref replaced_path)) => replaced_path,
102                             _ => return,
103                         };
104
105                         let mut applicability = Applicability::MachineApplicable;
106                         span_lint_and_sugg(
107                             cx,
108                             MEM_REPLACE_OPTION_WITH_NONE,
109                             expr.span,
110                             "replacing an `Option` with `None`",
111                             "consider `Option::take()` instead",
112                             format!("{}.take()", snippet_with_applicability(cx, replaced_path.span, "", &mut applicability)),
113                             applicability,
114                         );
115                     }
116                 }
117                 if let ExprKind::Call(ref repl_func, ref repl_args) = func_args[1].kind {
118                     if_chain! {
119                         if repl_args.is_empty();
120                         if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind;
121                         if let Some(repl_def_id) = cx.tables.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id();
122                         then {
123                             if match_def_path(cx, repl_def_id, &paths::MEM_UNINITIALIZED) {
124                                 span_help_and_lint(
125                                     cx,
126                                     MEM_REPLACE_WITH_UNINIT,
127                                     expr.span,
128                                     "replacing with `mem::uninitialized()`",
129                                     "consider using the `take_mut` crate instead",
130                                 );
131                             } else if match_def_path(cx, repl_def_id, &paths::MEM_ZEROED) &&
132                                     !cx.tables.expr_ty(&func_args[1]).is_primitive() {
133                                 span_help_and_lint(
134                                     cx,
135                                     MEM_REPLACE_WITH_UNINIT,
136                                     expr.span,
137                                     "replacing with `mem::zeroed()`",
138                                     "consider using a default value or the `take_mut` crate instead",
139                                 );
140                             }
141                         }
142                     }
143                 }
144             }
145         }
146     }
147 }