1 use crate::utils::{match_def_path, match_qpath, paths, snippet_with_applicability, span_lint_and_sugg};
2 use if_chain::if_chain;
3 use rustc::hir::{Expr, ExprKind, MutMutable, QPath};
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::{declare_lint_pass, declare_tool_lint};
6 use rustc_errors::Applicability;
9 /// **What it does:** Checks for `mem::replace()` on an `Option` with
12 /// **Why is this bad?** `Option` already has the method `take()` for
13 /// taking its current value (Some(..) or None) and replacing it with
16 /// **Known problems:** None.
22 /// let mut an_option = Some(0);
23 /// let replaced = mem::replace(&mut an_option, None);
25 /// Is better expressed with:
27 /// let mut an_option = Some(0);
28 /// let taken = an_option.take();
30 pub MEM_REPLACE_OPTION_WITH_NONE,
32 "replacing an `Option` with `None` instead of `take()`"
35 declare_lint_pass!(MemReplace => [MEM_REPLACE_OPTION_WITH_NONE]);
37 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemReplace {
38 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
40 // Check that `expr` is a call to `mem::replace()`
41 if let ExprKind::Call(ref func, ref func_args) = expr.node;
42 if func_args.len() == 2;
43 if let ExprKind::Path(ref func_qpath) = func.node;
44 if let Some(def_id) = cx.tables.qpath_res(func_qpath, func.hir_id).opt_def_id();
45 if match_def_path(cx, def_id, &paths::MEM_REPLACE);
47 // Check that second argument is `Option::None`
48 if let ExprKind::Path(ref replacement_qpath) = func_args[1].node;
49 if match_qpath(replacement_qpath, &paths::OPTION_NONE);
52 // Since this is a late pass (already type-checked),
53 // and we already know that the second argument is an
54 // `Option`, we do not need to check the first
55 // argument's type. All that's left is to get
57 let replaced_path = match func_args[0].node {
58 ExprKind::AddrOf(MutMutable, ref replaced) => {
59 if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.node {
65 ExprKind::Path(QPath::Resolved(None, ref replaced_path)) => replaced_path,
69 let mut applicability = Applicability::MachineApplicable;
72 MEM_REPLACE_OPTION_WITH_NONE,
74 "replacing an `Option` with `None`",
75 "consider `Option::take()` instead",
76 format!("{}.take()", snippet_with_applicability(cx, replaced_path.span, "", &mut applicability)),