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, match_def_path, meets_msrv, paths};
4 use clippy_utils::{is_diagnostic_assoc_item, is_lang_ctor};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::def_id::DefId;
8 use rustc_hir::LangItem::OptionNone;
9 use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, QPath};
10 use rustc_lint::{LateContext, LateLintPass, LintContext};
11 use rustc_middle::lint::in_external_macro;
12 use rustc_semver::RustcVersion;
13 use rustc_session::{declare_tool_lint, impl_lint_pass};
14 use rustc_span::source_map::Span;
15 use rustc_span::symbol::sym;
17 declare_clippy_lint! {
18 /// **What it does:** Checks for `mem::replace()` on an `Option` with
21 /// **Why is this bad?** `Option` already has the method `take()` for
22 /// taking its current value (Some(..) or None) and replacing it with
25 /// **Known problems:** None.
31 /// let mut an_option = Some(0);
32 /// let replaced = mem::replace(&mut an_option, None);
34 /// Is better expressed with:
36 /// let mut an_option = Some(0);
37 /// let taken = an_option.take();
39 pub MEM_REPLACE_OPTION_WITH_NONE,
41 "replacing an `Option` with `None` instead of `take()`"
44 declare_clippy_lint! {
45 /// **What it does:** Checks for `mem::replace(&mut _, mem::uninitialized())`
46 /// and `mem::replace(&mut _, mem::zeroed())`.
48 /// **Why is this bad?** This will lead to undefined behavior even if the
49 /// value is overwritten later, because the uninitialized value may be
50 /// observed in the case of a panic.
52 /// **Known problems:** None.
58 ///# fn may_panic(v: Vec<i32>) -> Vec<i32> { v }
60 /// #[allow(deprecated, invalid_value)]
61 /// fn myfunc (v: &mut Vec<i32>) {
62 /// let taken_v = unsafe { mem::replace(v, mem::uninitialized()) };
63 /// let new_v = may_panic(taken_v); // undefined behavior on panic
64 /// mem::forget(mem::replace(v, new_v));
68 /// The [take_mut](https://docs.rs/take_mut) crate offers a sound solution,
69 /// at the cost of either lazily creating a replacement value or aborting
70 /// on panic, to ensure that the uninitialized value cannot be observed.
71 pub MEM_REPLACE_WITH_UNINIT,
73 "`mem::replace(&mut _, mem::uninitialized())` or `mem::replace(&mut _, mem::zeroed())`"
76 declare_clippy_lint! {
77 /// **What it does:** Checks for `std::mem::replace` on a value of type
78 /// `T` with `T::default()`.
80 /// **Why is this bad?** `std::mem` module already has the method `take` to
81 /// take the current value and replace it with the default value of that type.
83 /// **Known problems:** None.
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 pub MEM_REPLACE_WITH_DEFAULT,
97 "replacing a value of type `T` with `T::default()` instead of using `std::mem::take`"
100 impl_lint_pass!(MemReplace =>
101 [MEM_REPLACE_OPTION_WITH_NONE, MEM_REPLACE_WITH_UNINIT, MEM_REPLACE_WITH_DEFAULT]);
103 fn check_replace_option_with_none(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
104 if let ExprKind::Path(ref replacement_qpath) = src.kind {
105 // Check that second argument is `Option::None`
106 if is_lang_ctor(cx, replacement_qpath, OptionNone) {
107 // Since this is a late pass (already type-checked),
108 // and we already know that the second argument is an
109 // `Option`, we do not need to check the first
110 // argument's type. All that's left is to get
112 let replaced_path = match dest.kind {
113 ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, replaced) => {
114 if let ExprKind::Path(QPath::Resolved(None, replaced_path)) = replaced.kind {
120 ExprKind::Path(QPath::Resolved(None, replaced_path)) => replaced_path,
124 let mut applicability = Applicability::MachineApplicable;
127 MEM_REPLACE_OPTION_WITH_NONE,
129 "replacing an `Option` with `None`",
130 "consider `Option::take()` instead",
133 snippet_with_applicability(cx, replaced_path.span, "", &mut applicability)
141 fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
143 // check if replacement is mem::MaybeUninit::uninit().assume_init()
144 if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(src.hir_id);
145 if cx.tcx.is_diagnostic_item(sym::assume_init, method_def_id);
147 let mut applicability = Applicability::MachineApplicable;
150 MEM_REPLACE_WITH_UNINIT,
152 "replacing with `mem::MaybeUninit::uninit().assume_init()`",
155 "std::ptr::read({})",
156 snippet_with_applicability(cx, dest.span, "", &mut applicability)
165 if let ExprKind::Call(repl_func, repl_args) = src.kind;
166 if repl_args.is_empty();
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 /// Returns true if the `def_id` associated with the `path` is recognized as a "default-equivalent"
200 /// constructor from the std library
201 fn is_default_equivalent_ctor(cx: &LateContext<'_>, def_id: DefId, path: &QPath<'_>) -> bool {
202 let std_types_symbols = &[
216 .any(|symbol| is_diagnostic_assoc_item(cx, def_id, *symbol))
218 if let QPath::TypeRelative(_, method) = path {
219 if method.ident.name == sym::new {
228 fn check_replace_with_default(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
230 if let ExprKind::Call(repl_func, _) = src.kind;
231 if !in_external_macro(cx.tcx.sess, expr_span);
232 if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind;
233 if let Some(repl_def_id) = cx.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id();
234 if is_diagnostic_assoc_item(cx, repl_def_id, sym::Default)
235 || is_default_equivalent_ctor(cx, repl_def_id, repl_func_qpath);
240 MEM_REPLACE_WITH_DEFAULT,
242 "replacing a value of type `T` with `T::default()` is better expressed using `std::mem::take`",
244 if !in_macro(expr_span) {
245 let suggestion = format!("std::mem::take({})", snippet(cx, dest.span, ""));
247 diag.span_suggestion(
251 Applicability::MachineApplicable
260 const MEM_REPLACE_WITH_DEFAULT_MSRV: RustcVersion = RustcVersion::new(1, 40, 0);
262 pub struct MemReplace {
263 msrv: Option<RustcVersion>,
268 pub fn new(msrv: Option<RustcVersion>) -> Self {
273 impl<'tcx> LateLintPass<'tcx> for MemReplace {
274 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
276 // Check that `expr` is a call to `mem::replace()`
277 if let ExprKind::Call(func, func_args) = expr.kind;
278 if let ExprKind::Path(ref func_qpath) = func.kind;
279 if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id();
280 if match_def_path(cx, def_id, &paths::MEM_REPLACE);
281 if let [dest, src] = func_args;
283 check_replace_option_with_none(cx, src, dest, expr.span);
284 check_replace_with_uninit(cx, src, dest, expr.span);
285 if meets_msrv(self.msrv.as_ref(), &MEM_REPLACE_WITH_DEFAULT_MSRV) {
286 check_replace_with_default(cx, src, dest, expr.span);
291 extract_msrv_attr!(LateContext);