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::ty::is_non_aggregate_primitive_type;
4 use clippy_utils::{is_default_equivalent, is_lang_ctor, meets_msrv, msrvs};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::LangItem::OptionNone;
8 use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, QPath};
9 use rustc_lint::{LateContext, LateLintPass};
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;
16 declare_clippy_lint! {
18 /// Checks for `mem::replace()` on an `Option` with
21 /// ### Why is this bad?
22 /// `Option` already has the method `take()` for
23 /// taking its current value (Some(..) or None) and replacing it with
30 /// let mut an_option = Some(0);
31 /// let replaced = mem::replace(&mut an_option, None);
33 /// Is better expressed with:
35 /// let mut an_option = Some(0);
36 /// let taken = an_option.take();
38 #[clippy::version = "1.31.0"]
39 pub MEM_REPLACE_OPTION_WITH_NONE,
41 "replacing an `Option` with `None` instead of `take()`"
44 declare_clippy_lint! {
46 /// Checks for `mem::replace(&mut _, mem::uninitialized())`
47 /// and `mem::replace(&mut _, mem::zeroed())`.
49 /// ### Why is this bad?
50 /// This will lead to undefined behavior even if the
51 /// value is overwritten later, because the uninitialized value may be
52 /// observed in the case of a panic.
57 ///# fn may_panic(v: Vec<i32>) -> Vec<i32> { v }
59 /// #[allow(deprecated, invalid_value)]
60 /// fn myfunc (v: &mut Vec<i32>) {
61 /// let taken_v = unsafe { mem::replace(v, mem::uninitialized()) };
62 /// let new_v = may_panic(taken_v); // undefined behavior on panic
63 /// mem::forget(mem::replace(v, new_v));
67 /// The [take_mut](https://docs.rs/take_mut) crate offers a sound solution,
68 /// at the cost of either lazily creating a replacement value or aborting
69 /// on panic, to ensure that the uninitialized value cannot be observed.
70 #[clippy::version = "1.39.0"]
71 pub MEM_REPLACE_WITH_UNINIT,
73 "`mem::replace(&mut _, mem::uninitialized())` or `mem::replace(&mut _, mem::zeroed())`"
76 declare_clippy_lint! {
78 /// Checks for `std::mem::replace` on a value of type
79 /// `T` with `T::default()`.
81 /// ### Why is this bad?
82 /// `std::mem` module already has the method `take` to
83 /// take the current value and replace it with the default value of that type.
87 /// let mut text = String::from("foo");
88 /// let replaced = std::mem::replace(&mut text, String::default());
90 /// Is better expressed with:
92 /// let mut text = String::from("foo");
93 /// let taken = std::mem::take(&mut text);
95 #[clippy::version = "1.42.0"]
96 pub MEM_REPLACE_WITH_DEFAULT,
98 "replacing a value of type `T` with `T::default()` instead of using `std::mem::take`"
101 impl_lint_pass!(MemReplace =>
102 [MEM_REPLACE_OPTION_WITH_NONE, MEM_REPLACE_WITH_UNINIT, MEM_REPLACE_WITH_DEFAULT]);
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 is_lang_ctor(cx, replacement_qpath, OptionNone) {
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
113 let replaced_path = match dest.kind {
114 ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, replaced) => {
115 if let ExprKind::Path(QPath::Resolved(None, replaced_path)) = replaced.kind {
121 ExprKind::Path(QPath::Resolved(None, replaced_path)) => replaced_path,
125 let mut applicability = Applicability::MachineApplicable;
128 MEM_REPLACE_OPTION_WITH_NONE,
130 "replacing an `Option` with `None`",
131 "consider `Option::take()` instead",
134 snippet_with_applicability(cx, replaced_path.span, "", &mut applicability)
142 fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
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);
148 let mut applicability = Applicability::MachineApplicable;
151 MEM_REPLACE_WITH_UNINIT,
153 "replacing with `mem::MaybeUninit::uninit().assume_init()`",
156 "std::ptr::read({})",
157 snippet_with_applicability(cx, dest.span, "", &mut applicability)
166 if let ExprKind::Call(repl_func, []) = src.kind;
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();
170 if cx.tcx.is_diagnostic_item(sym::mem_uninitialized, repl_def_id) {
171 let mut applicability = Applicability::MachineApplicable;
174 MEM_REPLACE_WITH_UNINIT,
176 "replacing with `mem::uninitialized()`",
179 "std::ptr::read({})",
180 snippet_with_applicability(cx, dest.span, "", &mut applicability)
184 } else if cx.tcx.is_diagnostic_item(sym::mem_zeroed, repl_def_id) &&
185 !cx.typeck_results().expr_ty(src).is_primitive() {
188 MEM_REPLACE_WITH_UNINIT,
190 "replacing with `mem::zeroed()`",
192 "consider using a default value or the `take_mut` crate instead",
199 fn check_replace_with_default(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
200 // disable lint for primitives
201 let expr_type = cx.typeck_results().expr_ty_adjusted(src);
202 if is_non_aggregate_primitive_type(expr_type) {
205 // disable lint for Option since it is covered in another lint
206 if let ExprKind::Path(q) = &src.kind {
207 if is_lang_ctor(cx, q, OptionNone) {
211 if is_default_equivalent(cx, src) && !in_external_macro(cx.tcx.sess, expr_span) {
214 MEM_REPLACE_WITH_DEFAULT,
216 "replacing a value of type `T` with `T::default()` is better expressed using `std::mem::take`",
218 if !expr_span.from_expansion() {
219 let suggestion = format!("std::mem::take({})", snippet(cx, dest.span, ""));
221 diag.span_suggestion(
225 Applicability::MachineApplicable,
233 pub struct MemReplace {
234 msrv: Option<RustcVersion>,
239 pub fn new(msrv: Option<RustcVersion>) -> Self {
244 impl<'tcx> LateLintPass<'tcx> for MemReplace {
245 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
247 // Check that `expr` is a call to `mem::replace()`
248 if let ExprKind::Call(func, [dest, src]) = expr.kind;
249 if let ExprKind::Path(ref func_qpath) = func.kind;
250 if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id();
251 if cx.tcx.is_diagnostic_item(sym::mem_replace, def_id);
253 check_replace_option_with_none(cx, src, dest, expr.span);
254 check_replace_with_uninit(cx, src, dest, expr.span);
255 if meets_msrv(self.msrv, msrvs::MEM_TAKE) {
256 check_replace_with_default(cx, src, dest, expr.span);
261 extract_msrv_attr!(LateContext);