Skip to content

Commit b5c4342

Browse files
authored
Merge pull request #3195 from JayKickliter/jsk/mem_replace_opt_w_none
Add lint for `mem::replace(.., None)`.
2 parents 8e9f1a9 + 79cda3b commit b5c4342

File tree

7 files changed

+117
-1
lines changed

7 files changed

+117
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -744,6 +744,7 @@ All notable changes to this project will be documented in this file.
744744
[`match_wild_err_arm`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#match_wild_err_arm
745745
[`maybe_infinite_iter`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#maybe_infinite_iter
746746
[`mem_forget`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#mem_forget
747+
[`mem_replace_option_with_none`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#mem_replace_option_with_none
747748
[`min_max`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#min_max
748749
[`misaligned_transmute`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#misaligned_transmute
749750
[`misrefactored_assign_op`]: https://rust-lang-nursery.github.io/rust-clippy/master/index.html#misrefactored_assign_op

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ We are currently in the process of discussing Clippy 1.0 via the RFC process in
99

1010
A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code.
1111

12-
[There are 276 lints included in this crate!](https://rust-lang-nursery.github.io/rust-clippy/master/index.html)
12+
[There are 277 lints included in this crate!](https://rust-lang-nursery.github.io/rust-clippy/master/index.html)
1313

1414
We have a bunch of lint categories to allow you to choose how much Clippy is supposed to ~~annoy~~ help you:
1515

clippy_lints/src/lib.rs

Lines changed: 4 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);
@@ -591,6 +593,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
591593
matches::MATCH_REF_PATS,
592594
matches::MATCH_WILD_ERR_ARM,
593595
matches::SINGLE_MATCH,
596+
mem_replace::MEM_REPLACE_OPTION_WITH_NONE,
594597
methods::CHARS_LAST_CMP,
595598
methods::CHARS_NEXT_CMP,
596599
methods::CLONE_DOUBLE_REF,
@@ -748,6 +751,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
748751
matches::MATCH_REF_PATS,
749752
matches::MATCH_WILD_ERR_ARM,
750753
matches::SINGLE_MATCH,
754+
mem_replace::MEM_REPLACE_OPTION_WITH_NONE,
751755
methods::CHARS_LAST_CMP,
752756
methods::GET_UNWRAP,
753757
methods::ITER_CLONED_COLLECT,

clippy_lints/src/mem_replace.rs

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
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, 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+
// Check that `expr` is a call to `mem::replace()`
44+
if let ExprKind::Call(ref func, ref func_args) = expr.node;
45+
if func_args.len() == 2;
46+
if let ExprKind::Path(ref func_qpath) = func.node;
47+
if let Some(def_id) = opt_def_id(cx.tables.qpath_def(func_qpath, func.hir_id));
48+
if match_def_path(cx.tcx, def_id, &paths::MEM_REPLACE);
49+
50+
// Check that second argument is `Option::None`
51+
if let ExprKind::Path(ref replacement_qpath) = func_args[1].node;
52+
if match_qpath(replacement_qpath, &paths::OPTION_NONE);
53+
54+
then {
55+
// Since this is a late pass (already type-checked),
56+
// and we already know that the second argument is an
57+
// `Option`, we do not need to check the first
58+
// argument's type. All that's left is to get
59+
// replacee's path.
60+
let replaced_path = match func_args[0].node {
61+
ExprKind::AddrOf(MutMutable, ref replaced) => {
62+
if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.node {
63+
replaced_path
64+
} else {
65+
return
66+
}
67+
},
68+
ExprKind::Path(QPath::Resolved(None, ref replaced_path)) => replaced_path,
69+
_ => return,
70+
};
71+
72+
span_lint_and_sugg(
73+
cx,
74+
MEM_REPLACE_OPTION_WITH_NONE,
75+
expr.span,
76+
"replacing an `Option` with `None`",
77+
"consider `Option::take()` instead",
78+
format!("{}.take()", snippet(cx, replaced_path.span, ""))
79+
);
80+
}
81+
}
82+
}
83+
}

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: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
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+
let an_option = &mut Some(1);
10+
let _ = mem::replace(an_option, None);
11+
}

tests/ui/mem_replace.stderr

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
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: replacing an `Option` with `None`
10+
--> $DIR/mem_replace.rs:10:13
11+
|
12+
10 | let _ = mem::replace(an_option, None);
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider `Option::take()` instead: `an_option.take()`
14+
15+
error: aborting due to 2 previous errors
16+

0 commit comments

Comments
 (0)