]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/mem_replace.rs
mem_replace: make examples compilable.
[rust.git] / clippy_lints / src / mem_replace.rs
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;
6
7 /// **What it does:** Checks for `mem::replace()` on an `Option` with
8 /// `None`.
9 ///
10 /// **Why is this bad?** `Option` already has the method `take()` for
11 /// taking its current value (Some(..) or None) and replacing it with
12 /// `None`.
13 ///
14 /// **Known problems:** None.
15 ///
16 /// **Example:**
17 /// ```rust
18 /// let mut an_option = Some(0);
19 /// let replaced = mem::replace(&mut an_option, None);
20 /// ```
21 /// Is better expressed with:
22 /// ```rust
23 /// let mut an_option = Some(0);
24 /// let taken = an_option.take();
25 /// ```
26 declare_clippy_lint! {
27     pub MEM_REPLACE_OPTION_WITH_NONE,
28     style,
29     "replacing an `Option` with `None` instead of `take()`"
30 }
31
32 pub struct MemReplace;
33
34 impl LintPass for MemReplace {
35     fn get_lints(&self) -> LintArray {
36         lint_array![MEM_REPLACE_OPTION_WITH_NONE]
37     }
38 }
39
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemReplace {
41     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
42         if_chain! {
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;
53             then {
54                 let sugg = format!("{}.take()", snippet(cx, replaced_path.span, ""));
55                 span_lint_and_sugg(
56                     cx,
57                     MEM_REPLACE_OPTION_WITH_NONE,
58                     expr.span,
59                     "replacing an `Option` with `None`",
60                     "consider `Option::take()` instead",
61                     sugg
62                 );
63             }
64         }
65     }
66 }