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.
10 use crate::rustc::hir::{Expr, ExprKind, MutMutable, QPath};
11 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use crate::rustc_errors::Applicability;
14 use crate::utils::{match_def_path, match_qpath, opt_def_id, paths, snippet_with_applicability, span_lint_and_sugg};
15 use if_chain::if_chain;
17 /// **What it does:** Checks for `mem::replace()` on an `Option` with
20 /// **Why is this bad?** `Option` already has the method `take()` for
21 /// taking its current value (Some(..) or None) and replacing it with
24 /// **Known problems:** None.
28 /// let mut an_option = Some(0);
29 /// let replaced = mem::replace(&mut an_option, None);
31 /// Is better expressed with:
33 /// let mut an_option = Some(0);
34 /// let taken = an_option.take();
36 declare_clippy_lint! {
37 pub MEM_REPLACE_OPTION_WITH_NONE,
39 "replacing an `Option` with `None` instead of `take()`"
42 pub struct MemReplace;
44 impl LintPass for MemReplace {
45 fn get_lints(&self) -> LintArray {
46 lint_array![MEM_REPLACE_OPTION_WITH_NONE]
50 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemReplace {
51 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
53 // Check that `expr` is a call to `mem::replace()`
54 if let ExprKind::Call(ref func, ref func_args) = expr.node;
55 if func_args.len() == 2;
56 if let ExprKind::Path(ref func_qpath) = func.node;
57 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(func_qpath, func.hir_id));
58 if match_def_path(cx.tcx, def_id, &paths::MEM_REPLACE);
60 // Check that second argument is `Option::None`
61 if let ExprKind::Path(ref replacement_qpath) = func_args[1].node;
62 if match_qpath(replacement_qpath, &paths::OPTION_NONE);
65 // Since this is a late pass (already type-checked),
66 // and we already know that the second argument is an
67 // `Option`, we do not need to check the first
68 // argument's type. All that's left is to get
70 let replaced_path = match func_args[0].node {
71 ExprKind::AddrOf(MutMutable, ref replaced) => {
72 if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.node {
78 ExprKind::Path(QPath::Resolved(None, ref replaced_path)) => replaced_path,
82 let mut applicability = Applicability::MachineApplicable;
85 MEM_REPLACE_OPTION_WITH_NONE,
87 "replacing an `Option` with `None`",
88 "consider `Option::take()` instead",
89 format!("{}.take()", snippet_with_applicability(cx, replaced_path.span, "", &mut applicability)),