2 in_macro, match_def_path, match_qpath, meets_msrv, paths, snippet, snippet_with_applicability, span_lint_and_help,
3 span_lint_and_sugg, span_lint_and_then,
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::def_id::DefId;
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 use clippy_utils::is_diagnostic_assoc_item;
18 declare_clippy_lint! {
19 /// **What it does:** Checks for `mem::replace()` on an `Option` with
22 /// **Why is this bad?** `Option` already has the method `take()` for
23 /// taking its current value (Some(..) or None) and replacing it with
26 /// **Known problems:** None.
32 /// let mut an_option = Some(0);
33 /// let replaced = mem::replace(&mut an_option, None);
35 /// Is better expressed with:
37 /// let mut an_option = Some(0);
38 /// let taken = an_option.take();
40 pub MEM_REPLACE_OPTION_WITH_NONE,
42 "replacing an `Option` with `None` instead of `take()`"
45 declare_clippy_lint! {
46 /// **What it does:** Checks for `mem::replace(&mut _, mem::uninitialized())`
47 /// and `mem::replace(&mut _, mem::zeroed())`.
49 /// **Why is this bad?** 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.
53 /// **Known problems:** None.
59 ///# fn may_panic(v: Vec<i32>) -> Vec<i32> { v }
61 /// #[allow(deprecated, invalid_value)]
62 /// fn myfunc (v: &mut Vec<i32>) {
63 /// let taken_v = unsafe { mem::replace(v, mem::uninitialized()) };
64 /// let new_v = may_panic(taken_v); // undefined behavior on panic
65 /// mem::forget(mem::replace(v, new_v));
69 /// The [take_mut](https://docs.rs/take_mut) crate offers a sound solution,
70 /// at the cost of either lazily creating a replacement value or aborting
71 /// on panic, to ensure that the uninitialized value cannot be observed.
72 pub MEM_REPLACE_WITH_UNINIT,
74 "`mem::replace(&mut _, mem::uninitialized())` or `mem::replace(&mut _, mem::zeroed())`"
77 declare_clippy_lint! {
78 /// **What it does:** Checks for `std::mem::replace` on a value of type
79 /// `T` with `T::default()`.
81 /// **Why is this bad?** `std::mem` module already has the method `take` to
82 /// take the current value and replace it with the default value of that type.
84 /// **Known problems:** None.
88 /// let mut text = String::from("foo");
89 /// let replaced = std::mem::replace(&mut text, String::default());
91 /// Is better expressed with:
93 /// let mut text = String::from("foo");
94 /// let taken = std::mem::take(&mut text);
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 match_qpath(replacement_qpath, &paths::OPTION_NONE) {
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, ref replaced) => {
115 if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.kind {
121 ExprKind::Path(QPath::Resolved(None, ref 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(ref repl_func, ref repl_args) = src.kind;
167 if repl_args.is_empty();
168 if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind;
169 if let Some(repl_def_id) = cx.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id();
171 if cx.tcx.is_diagnostic_item(sym::mem_uninitialized, repl_def_id) {
172 let mut applicability = Applicability::MachineApplicable;
175 MEM_REPLACE_WITH_UNINIT,
177 "replacing with `mem::uninitialized()`",
180 "std::ptr::read({})",
181 snippet_with_applicability(cx, dest.span, "", &mut applicability)
185 } else if cx.tcx.is_diagnostic_item(sym::mem_zeroed, repl_def_id) &&
186 !cx.typeck_results().expr_ty(src).is_primitive() {
189 MEM_REPLACE_WITH_UNINIT,
191 "replacing with `mem::zeroed()`",
193 "consider using a default value or the `take_mut` crate instead",
200 /// Returns true if the `def_id` associated with the `path` is recognized as a "default-equivalent"
201 /// constructor from the std library
202 fn is_default_equivalent_ctor(cx: &LateContext<'_>, def_id: DefId, path: &QPath<'_>) -> bool {
203 let std_types_symbols = &[
217 .any(|symbol| is_diagnostic_assoc_item(cx, def_id, *symbol))
219 if let QPath::TypeRelative(_, ref method) = path {
220 if method.ident.name == sym::new {
229 fn check_replace_with_default(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
230 if let ExprKind::Call(ref repl_func, _) = src.kind {
232 if !in_external_macro(cx.tcx.sess, expr_span);
233 if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind;
234 if let Some(repl_def_id) = cx.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id();
235 if is_diagnostic_assoc_item(cx, repl_def_id, sym::Default)
236 || is_default_equivalent_ctor(cx, repl_def_id, repl_func_qpath);
241 MEM_REPLACE_WITH_DEFAULT,
243 "replacing a value of type `T` with `T::default()` is better expressed using `std::mem::take`",
245 if !in_macro(expr_span) {
246 let suggestion = format!("std::mem::take({})", snippet(cx, dest.span, ""));
248 diag.span_suggestion(
252 Applicability::MachineApplicable
262 const MEM_REPLACE_WITH_DEFAULT_MSRV: RustcVersion = RustcVersion::new(1, 40, 0);
264 pub struct MemReplace {
265 msrv: Option<RustcVersion>,
270 pub fn new(msrv: Option<RustcVersion>) -> Self {
275 impl<'tcx> LateLintPass<'tcx> for MemReplace {
276 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
278 // Check that `expr` is a call to `mem::replace()`
279 if let ExprKind::Call(ref func, ref func_args) = expr.kind;
280 if let ExprKind::Path(ref func_qpath) = func.kind;
281 if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id();
282 if match_def_path(cx, def_id, &paths::MEM_REPLACE);
283 if let [dest, src] = &**func_args;
285 check_replace_option_with_none(cx, src, dest, expr.span);
286 check_replace_with_uninit(cx, src, dest, expr.span);
287 if meets_msrv(self.msrv.as_ref(), &MEM_REPLACE_WITH_DEFAULT_MSRV) {
288 check_replace_with_default(cx, src, dest, expr.span);
293 extract_msrv_attr!(LateContext);