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, is_diag_trait_item, is_lang_ctor, match_def_path, meets_msrv, msrvs, paths};
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::def_id::DefId;
7 use rustc_hir::LangItem::OptionNone;
8 use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, QPath};
9 use rustc_lint::{LateContext, LateLintPass, LintContext};
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 pub MEM_REPLACE_OPTION_WITH_NONE,
40 "replacing an `Option` with `None` instead of `take()`"
43 declare_clippy_lint! {
45 /// Checks for `mem::replace(&mut _, mem::uninitialized())`
46 /// and `mem::replace(&mut _, mem::zeroed())`.
48 /// ### Why is this bad?
49 /// This will lead to undefined behavior even if the
50 /// value is overwritten later, because the uninitialized value may be
51 /// observed in the case of a panic.
56 ///# fn may_panic(v: Vec<i32>) -> Vec<i32> { v }
58 /// #[allow(deprecated, invalid_value)]
59 /// fn myfunc (v: &mut Vec<i32>) {
60 /// let taken_v = unsafe { mem::replace(v, mem::uninitialized()) };
61 /// let new_v = may_panic(taken_v); // undefined behavior on panic
62 /// mem::forget(mem::replace(v, new_v));
66 /// The [take_mut](https://docs.rs/take_mut) crate offers a sound solution,
67 /// at the cost of either lazily creating a replacement value or aborting
68 /// on panic, to ensure that the uninitialized value cannot be observed.
69 pub MEM_REPLACE_WITH_UNINIT,
71 "`mem::replace(&mut _, mem::uninitialized())` or `mem::replace(&mut _, mem::zeroed())`"
74 declare_clippy_lint! {
76 /// Checks for `std::mem::replace` on a value of type
77 /// `T` with `T::default()`.
79 /// ### Why is this bad?
80 /// `std::mem` module already has the method `take` to
81 /// take the current value and replace it with the default value of that type.
85 /// let mut text = String::from("foo");
86 /// let replaced = std::mem::replace(&mut text, String::default());
88 /// Is better expressed with:
90 /// let mut text = String::from("foo");
91 /// let taken = std::mem::take(&mut text);
93 pub MEM_REPLACE_WITH_DEFAULT,
95 "replacing a value of type `T` with `T::default()` instead of using `std::mem::take`"
98 impl_lint_pass!(MemReplace =>
99 [MEM_REPLACE_OPTION_WITH_NONE, MEM_REPLACE_WITH_UNINIT, MEM_REPLACE_WITH_DEFAULT]);
101 fn check_replace_option_with_none(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
102 if let ExprKind::Path(ref replacement_qpath) = src.kind {
103 // Check that second argument is `Option::None`
104 if is_lang_ctor(cx, replacement_qpath, OptionNone) {
105 // Since this is a late pass (already type-checked),
106 // and we already know that the second argument is an
107 // `Option`, we do not need to check the first
108 // argument's type. All that's left is to get
110 let replaced_path = match dest.kind {
111 ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, replaced) => {
112 if let ExprKind::Path(QPath::Resolved(None, replaced_path)) = replaced.kind {
118 ExprKind::Path(QPath::Resolved(None, replaced_path)) => replaced_path,
122 let mut applicability = Applicability::MachineApplicable;
125 MEM_REPLACE_OPTION_WITH_NONE,
127 "replacing an `Option` with `None`",
128 "consider `Option::take()` instead",
131 snippet_with_applicability(cx, replaced_path.span, "", &mut applicability)
139 fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
141 // check if replacement is mem::MaybeUninit::uninit().assume_init()
142 if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(src.hir_id);
143 if cx.tcx.is_diagnostic_item(sym::assume_init, method_def_id);
145 let mut applicability = Applicability::MachineApplicable;
148 MEM_REPLACE_WITH_UNINIT,
150 "replacing with `mem::MaybeUninit::uninit().assume_init()`",
153 "std::ptr::read({})",
154 snippet_with_applicability(cx, dest.span, "", &mut applicability)
163 if let ExprKind::Call(repl_func, repl_args) = src.kind;
164 if repl_args.is_empty();
165 if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind;
166 if let Some(repl_def_id) = cx.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id();
168 if cx.tcx.is_diagnostic_item(sym::mem_uninitialized, repl_def_id) {
169 let mut applicability = Applicability::MachineApplicable;
172 MEM_REPLACE_WITH_UNINIT,
174 "replacing with `mem::uninitialized()`",
177 "std::ptr::read({})",
178 snippet_with_applicability(cx, dest.span, "", &mut applicability)
182 } else if cx.tcx.is_diagnostic_item(sym::mem_zeroed, repl_def_id) &&
183 !cx.typeck_results().expr_ty(src).is_primitive() {
186 MEM_REPLACE_WITH_UNINIT,
188 "replacing with `mem::zeroed()`",
190 "consider using a default value or the `take_mut` crate instead",
197 /// Returns true if the `def_id` associated with the `path` is recognized as a "default-equivalent"
198 /// constructor from the std library
199 fn is_default_equivalent_ctor(cx: &LateContext<'_>, def_id: DefId, path: &QPath<'_>) -> bool {
200 let std_types_symbols = &[
212 if let QPath::TypeRelative(_, method) = path {
213 if method.ident.name == sym::new {
214 if let Some(impl_did) = cx.tcx.impl_of_method(def_id) {
215 if let Some(adt) = cx.tcx.type_of(impl_did).ty_adt_def() {
216 return std_types_symbols
218 .any(|&symbol| cx.tcx.is_diagnostic_item(symbol, adt.did));
226 fn check_replace_with_default(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
228 if let ExprKind::Call(repl_func, _) = src.kind;
229 if !in_external_macro(cx.tcx.sess, expr_span);
230 if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind;
231 if let Some(repl_def_id) = cx.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id();
232 if is_diag_trait_item(cx, repl_def_id, sym::Default)
233 || is_default_equivalent_ctor(cx, repl_def_id, repl_func_qpath);
238 MEM_REPLACE_WITH_DEFAULT,
240 "replacing a value of type `T` with `T::default()` is better expressed using `std::mem::take`",
242 if !in_macro(expr_span) {
243 let suggestion = format!("std::mem::take({})", snippet(cx, dest.span, ""));
245 diag.span_suggestion(
249 Applicability::MachineApplicable
258 pub struct MemReplace {
259 msrv: Option<RustcVersion>,
264 pub fn new(msrv: Option<RustcVersion>) -> Self {
269 impl<'tcx> LateLintPass<'tcx> for MemReplace {
270 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
272 // Check that `expr` is a call to `mem::replace()`
273 if let ExprKind::Call(func, func_args) = expr.kind;
274 if let ExprKind::Path(ref func_qpath) = func.kind;
275 if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id();
276 if match_def_path(cx, def_id, &paths::MEM_REPLACE);
277 if let [dest, src] = func_args;
279 check_replace_option_with_none(cx, src, dest, expr.span);
280 check_replace_with_uninit(cx, src, dest, expr.span);
281 if meets_msrv(self.msrv.as_ref(), &msrvs::MEM_TAKE) {
282 check_replace_with_default(cx, src, dest, expr.span);
287 extract_msrv_attr!(LateContext);