Skip to content

Commit 598df08

Browse files
committed
Add lint for mem::replace(.., None).
Suggest `Option::take()` as an alternative.
1 parent 3fee6d6 commit 598df08

File tree

5 files changed

+89
-0
lines changed

5 files changed

+89
-0
lines changed

clippy_lints/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,7 @@ pub mod map_clone;
133133
pub mod map_unit_fn;
134134
pub mod matches;
135135
pub mod mem_forget;
136+
pub mod mem_replace;
136137
pub mod methods;
137138
pub mod minmax;
138139
pub mod misc;
@@ -380,6 +381,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
380381
reg.register_late_lint_pass(box neg_multiply::NegMultiply);
381382
reg.register_early_lint_pass(box unsafe_removed_from_name::UnsafeNameRemoval);
382383
reg.register_late_lint_pass(box mem_forget::MemForget);
384+
reg.register_late_lint_pass(box mem_replace::MemReplace);
383385
reg.register_late_lint_pass(box arithmetic::Arithmetic::default());
384386
reg.register_late_lint_pass(box assign_ops::AssignOps);
385387
reg.register_late_lint_pass(box let_if_seq::LetIfSeq);
@@ -748,6 +750,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
748750
matches::MATCH_REF_PATS,
749751
matches::MATCH_WILD_ERR_ARM,
750752
matches::SINGLE_MATCH,
753+
mem_replace::MEM_REPLACE_OPTION_WITH_NONE,
751754
methods::CHARS_LAST_CMP,
752755
methods::GET_UNWRAP,
753756
methods::ITER_CLONED_COLLECT,

clippy_lints/src/mem_replace.rs

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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 an_option = Some(0);
19+
/// let replaced = mem::replace(&mut an_option, None);
20+
/// ```
21+
/// Is better expressed with:
22+
/// ```rust
23+
/// let 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+
}

clippy_lints/src/utils/paths.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ pub const LINKED_LIST: [&str; 4] = ["alloc", "collections", "linked_list", "Link
4747
pub const LINT: [&str; 3] = ["rustc", "lint", "Lint"];
4848
pub const LINT_ARRAY: [&str; 3] = ["rustc", "lint", "LintArray"];
4949
pub const MEM_FORGET: [&str; 3] = ["core", "mem", "forget"];
50+
pub const MEM_REPLACE: [&str; 3] = ["core", "mem", "replace"];
5051
pub const MEM_UNINIT: [&str; 3] = ["core", "mem", "uninitialized"];
5152
pub const MEM_ZEROED: [&str; 3] = ["core", "mem", "zeroed"];
5253
pub const MUTEX: [&str; 4] = ["std", "sync", "mutex", "Mutex"];

tests/ui/mem_replace.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#![feature(tool_lints)]
2+
#![warn(clippy::all, clippy::style, clippy::mem_replace_option_with_none)]
3+
4+
use std::mem;
5+
6+
fn main() {
7+
let mut an_option = Some(1);
8+
let _ = mem::replace(&mut an_option, None);
9+
}

tests/ui/mem_replace.stderr

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
error: replacing an `Option` with `None`
2+
--> $DIR/mem_replace.rs:8:13
3+
|
4+
8 | let _ = mem::replace(&mut an_option, None);
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider `Option::take()` instead: `an_option.take()`
6+
|
7+
= note: `-D clippy::mem-replace-option-with-none` implied by `-D warnings`
8+
9+
error: aborting due to previous error
10+

0 commit comments

Comments
 (0)