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, match_type, 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 if let ExprKind::Call(ref func, ref func_args) = expr.node;
44 if func_args.len() == 2;
45 if let ExprKind::Path(ref func_qpath) = func.node;
46 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(func_qpath, func.hir_id));
47 if match_def_path(cx.tcx, def_id, &paths::MEM_REPLACE);
48 if let ExprKind::AddrOf(MutMutable, ref replaced) = func_args[0].node;
49 if match_type(cx, cx.tables.expr_ty(replaced), &paths::OPTION);
50 if let ExprKind::Path(ref replacement_qpath) = func_args[1].node;
51 if match_qpath(replacement_qpath, &paths::OPTION_NONE);
52 if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.node;
54 let sugg = format!("{}.take()", snippet(cx, replaced_path.span, ""));
57 MEM_REPLACE_OPTION_WITH_NONE,
59 "replacing an `Option` with `None`",
60 "consider `Option::take()` instead",