1 use crate::rustc::hir::{Expr, ExprKind, MutMutable, QPath};
2 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
3 use crate::rustc::{declare_tool_lint, lint_array};
4 use crate::utils::{match_def_path, match_qpath, opt_def_id, paths, snippet, span_lint_and_sugg};
5 use if_chain::if_chain;
7 /// **What it does:** Checks for `mem::replace()` on an `Option` with
10 /// **Why is this bad?** `Option` already has the method `take()` for
11 /// taking its current value (Some(..) or None) and replacing it with
14 /// **Known problems:** None.
18 /// let mut an_option = Some(0);
19 /// let replaced = mem::replace(&mut an_option, None);
21 /// Is better expressed with:
23 /// let mut an_option = Some(0);
24 /// let taken = an_option.take();
26 declare_clippy_lint! {
27 pub MEM_REPLACE_OPTION_WITH_NONE,
29 "replacing an `Option` with `None` instead of `take()`"
32 pub struct MemReplace;
34 impl LintPass for MemReplace {
35 fn get_lints(&self) -> LintArray {
36 lint_array![MEM_REPLACE_OPTION_WITH_NONE]
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemReplace {
41 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
43 // Check that `expr` is a call to `mem::replace()`
44 if let ExprKind::Call(ref func, ref func_args) = expr.node;
45 if func_args.len() == 2;
46 if let ExprKind::Path(ref func_qpath) = func.node;
47 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(func_qpath, func.hir_id));
48 if match_def_path(cx.tcx, def_id, &paths::MEM_REPLACE);
50 // Check that second argument is `Option::None`
51 if let ExprKind::Path(ref replacement_qpath) = func_args[1].node;
52 if match_qpath(replacement_qpath, &paths::OPTION_NONE);
55 // Since this is a late pass (already type-checked),
56 // and we already know that the second argument is an
57 // `Option`, we do not need to check if the first
58 // argument's type. All that's left is to get
60 let replaced_path = match func_args[0].node {
61 ExprKind::AddrOf(MutMutable, ref replaced) => {
62 if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.node {
68 ExprKind::Path(QPath::Resolved(None, ref replaced_path)) => replaced_path,
74 MEM_REPLACE_OPTION_WITH_NONE,
76 "replacing an `Option` with `None`",
77 "consider `Option::take()` instead",
78 format!("{}.take()", snippet(cx, replaced_path.span, ""))