1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 use crate::rustc::hir::{Expr, ExprKind, MutMutable, QPath};
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::rustc_errors::Applicability;
15 use crate::utils::{match_def_path, match_qpath, opt_def_id, paths, snippet_with_applicability, span_lint_and_sugg};
16 use if_chain::if_chain;
18 /// **What it does:** Checks for `mem::replace()` on an `Option` with
21 /// **Why is this bad?** `Option` already has the method `take()` for
22 /// taking its current value (Some(..) or None) and replacing it with
25 /// **Known problems:** None.
29 /// let mut an_option = Some(0);
30 /// let replaced = mem::replace(&mut an_option, None);
32 /// Is better expressed with:
34 /// let mut an_option = Some(0);
35 /// let taken = an_option.take();
37 declare_clippy_lint! {
38 pub MEM_REPLACE_OPTION_WITH_NONE,
40 "replacing an `Option` with `None` instead of `take()`"
43 pub struct MemReplace;
45 impl LintPass for MemReplace {
46 fn get_lints(&self) -> LintArray {
47 lint_array![MEM_REPLACE_OPTION_WITH_NONE]
51 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemReplace {
52 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
54 // Check that `expr` is a call to `mem::replace()`
55 if let ExprKind::Call(ref func, ref func_args) = expr.node;
56 if func_args.len() == 2;
57 if let ExprKind::Path(ref func_qpath) = func.node;
58 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(func_qpath, func.hir_id));
59 if match_def_path(cx.tcx, def_id, &paths::MEM_REPLACE);
61 // Check that second argument is `Option::None`
62 if let ExprKind::Path(ref replacement_qpath) = func_args[1].node;
63 if match_qpath(replacement_qpath, &paths::OPTION_NONE);
66 // Since this is a late pass (already type-checked),
67 // and we already know that the second argument is an
68 // `Option`, we do not need to check the first
69 // argument's type. All that's left is to get
71 let replaced_path = match func_args[0].node {
72 ExprKind::AddrOf(MutMutable, ref replaced) => {
73 if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.node {
79 ExprKind::Path(QPath::Resolved(None, ref replaced_path)) => replaced_path,
83 let mut applicability = Applicability::MachineApplicable;
86 MEM_REPLACE_OPTION_WITH_NONE,
88 "replacing an `Option` with `None`",
89 "consider `Option::take()` instead",
90 format!("{}.take()", snippet_with_applicability(cx, replaced_path.span, "", &mut applicability)),