2 in_macro, match_def_path, match_qpath, paths, snippet_with_applicability, span_help_and_lint, span_lint_and_sugg,
4 use if_chain::if_chain;
5 use rustc::declare_lint_pass;
6 use rustc::hir::{BorrowKind, Expr, ExprKind, HirVec, Mutability, QPath};
7 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintPass};
8 use rustc_errors::Applicability;
9 use rustc_session::declare_tool_lint;
11 declare_clippy_lint! {
12 /// **What it does:** Checks for `mem::replace()` on an `Option` with
15 /// **Why is this bad?** `Option` already has the method `take()` for
16 /// taking its current value (Some(..) or None) and replacing it with
19 /// **Known problems:** None.
25 /// let mut an_option = Some(0);
26 /// let replaced = mem::replace(&mut an_option, None);
28 /// Is better expressed with:
30 /// let mut an_option = Some(0);
31 /// let taken = an_option.take();
33 pub MEM_REPLACE_OPTION_WITH_NONE,
35 "replacing an `Option` with `None` instead of `take()`"
38 declare_clippy_lint! {
39 /// **What it does:** Checks for `mem::replace(&mut _, mem::uninitialized())`
40 /// and `mem::replace(&mut _, mem::zeroed())`.
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.
46 /// **Known problems:** None.
52 ///# fn may_panic(v: Vec<i32>) -> Vec<i32> { v }
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));
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,
67 "`mem::replace(&mut _, mem::uninitialized())` or `mem::replace(&mut _, mem::zeroed())`"
70 declare_clippy_lint! {
71 /// **What it does:** Checks for `std::mem::replace` on a value of type
72 /// `T` with `T::default()`.
74 /// **Why is this bad?** `std::mem` module already has the method `take` to
75 /// take the current value and replace it with the default value of that type.
77 /// **Known problems:** None.
81 /// let mut text = String::from("foo");
82 /// let replaced = std::mem::replace(&mut text, String::default());
84 /// Is better expressed with:
86 /// let mut text = String::from("foo");
87 /// let taken = std::mem::take(&mut text);
89 pub MEM_REPLACE_WITH_DEFAULT,
91 "replacing a value of type `T` with `T::default()` instead of using `std::mem::take`"
94 declare_lint_pass!(MemReplace =>
95 [MEM_REPLACE_OPTION_WITH_NONE, MEM_REPLACE_WITH_UNINIT, MEM_REPLACE_WITH_DEFAULT]);
97 fn check_replace_option_with_none(cx: &LateContext<'_, '_>, expr: &'_ Expr, args: &HirVec<Expr>) {
98 if let ExprKind::Path(ref replacement_qpath) = args[1].kind {
99 // Check that second argument is `Option::None`
100 if match_qpath(replacement_qpath, &paths::OPTION_NONE) {
101 // Since this is a late pass (already type-checked),
102 // and we already know that the second argument is an
103 // `Option`, we do not need to check the first
104 // argument's type. All that's left is to get
106 let replaced_path = match args[0].kind {
107 ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, ref replaced) => {
108 if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.kind {
114 ExprKind::Path(QPath::Resolved(None, ref replaced_path)) => replaced_path,
118 let mut applicability = Applicability::MachineApplicable;
121 MEM_REPLACE_OPTION_WITH_NONE,
123 "replacing an `Option` with `None`",
124 "consider `Option::take()` instead",
127 snippet_with_applicability(cx, replaced_path.span, "", &mut applicability)
135 fn check_replace_with_uninit(cx: &LateContext<'_, '_>, expr: &'_ Expr, args: &HirVec<Expr>) {
136 if let ExprKind::Call(ref repl_func, ref repl_args) = args[1].kind {
138 if repl_args.is_empty();
139 if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind;
140 if let Some(repl_def_id) = cx.tables.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id();
142 if match_def_path(cx, repl_def_id, &paths::MEM_UNINITIALIZED) {
145 MEM_REPLACE_WITH_UNINIT,
147 "replacing with `mem::uninitialized()`",
148 "consider using the `take_mut` crate instead",
150 } else if match_def_path(cx, repl_def_id, &paths::MEM_ZEROED) &&
151 !cx.tables.expr_ty(&args[1]).is_primitive() {
154 MEM_REPLACE_WITH_UNINIT,
156 "replacing with `mem::zeroed()`",
157 "consider using a default value or the `take_mut` crate instead",
165 fn check_replace_with_default(cx: &LateContext<'_, '_>, expr: &'_ Expr, args: &HirVec<Expr>) {
166 if let ExprKind::Call(ref repl_func, _) = args[1].kind {
168 if !in_macro(expr.span) && !in_external_macro(cx.tcx.sess, expr.span);
169 if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind;
170 if let Some(repl_def_id) = cx.tables.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id();
171 if match_def_path(cx, repl_def_id, &paths::DEFAULT_TRAIT_METHOD);
173 let mut applicability = Applicability::MachineApplicable;
177 MEM_REPLACE_WITH_DEFAULT,
179 "replacing a value of type `T` with `T::default()` is better expressed using `std::mem::take`",
182 "std::mem::take({})",
183 snippet_with_applicability(cx, args[0].span, "", &mut applicability)
192 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemReplace {
193 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
195 // Check that `expr` is a call to `mem::replace()`
196 if let ExprKind::Call(ref func, ref func_args) = expr.kind;
197 if func_args.len() == 2;
198 if let ExprKind::Path(ref func_qpath) = func.kind;
199 if let Some(def_id) = cx.tables.qpath_res(func_qpath, func.hir_id).opt_def_id();
200 if match_def_path(cx, def_id, &paths::MEM_REPLACE);
203 check_replace_option_with_none(cx, expr, &func_args);
204 check_replace_with_uninit(cx, expr, &func_args);
205 check_replace_with_default(cx, expr, &func_args);