Skip to content

Commit 342ac8e

Browse files
committed
New lint: mem_replace_option_with_some
`mem::replace(opt, Some(v))` can be replaced by `opt.replace(v)`.
1 parent 39bde6d commit 342ac8e

File tree

9 files changed

+133
-3
lines changed

9 files changed

+133
-3
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5812,6 +5812,7 @@ Released 2018-09-13
58125812
[`mem_discriminant_non_enum`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_discriminant_non_enum
58135813
[`mem_forget`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_forget
58145814
[`mem_replace_option_with_none`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_option_with_none
5815+
[`mem_replace_option_with_some`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_option_with_some
58155816
[`mem_replace_with_default`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_with_default
58165817
[`mem_replace_with_uninit`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_with_uninit
58175818
[`min_ident_chars`]: https://rust-lang.github.io/rust-clippy/master/index.html#min_ident_chars

book/src/lint_configuration.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -764,6 +764,7 @@ The minimum rust version that the project supports. Defaults to the `rust-versio
764764
* [`map_unwrap_or`](https://rust-lang.github.io/rust-clippy/master/index.html#map_unwrap_or)
765765
* [`map_with_unused_argument_over_ranges`](https://rust-lang.github.io/rust-clippy/master/index.html#map_with_unused_argument_over_ranges)
766766
* [`match_like_matches_macro`](https://rust-lang.github.io/rust-clippy/master/index.html#match_like_matches_macro)
767+
* [`mem_replace_option_with_some`](https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_option_with_some)
767768
* [`mem_replace_with_default`](https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_with_default)
768769
* [`missing_const_for_fn`](https://rust-lang.github.io/rust-clippy/master/index.html#missing_const_for_fn)
769770
* [`needless_borrow`](https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow)

clippy_config/src/conf.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -633,6 +633,7 @@ define_Conf! {
633633
map_unwrap_or,
634634
map_with_unused_argument_over_ranges,
635635
match_like_matches_macro,
636+
mem_replace_option_with_some,
636637
mem_replace_with_default,
637638
missing_const_for_fn,
638639
needless_borrow,

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,7 @@ pub static LINTS: &[&crate::LintInfo] = &[
362362
crate::matches::WILDCARD_ENUM_MATCH_ARM_INFO,
363363
crate::matches::WILDCARD_IN_OR_PATTERNS_INFO,
364364
crate::mem_replace::MEM_REPLACE_OPTION_WITH_NONE_INFO,
365+
crate::mem_replace::MEM_REPLACE_OPTION_WITH_SOME_INFO,
365366
crate::mem_replace::MEM_REPLACE_WITH_DEFAULT_INFO,
366367
crate::mem_replace::MEM_REPLACE_WITH_UNINIT_INFO,
367368
crate::methods::BIND_INSTEAD_OF_MAP_INFO,

clippy_lints/src/mem_replace.rs

Lines changed: 62 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use clippy_utils::{
88
is_default_equivalent, is_expr_used_or_unified, is_res_lang_ctor, path_res, peel_ref_operators, std_or_core,
99
};
1010
use rustc_errors::Applicability;
11-
use rustc_hir::LangItem::OptionNone;
11+
use rustc_hir::LangItem::{OptionNone, OptionSome};
1212
use rustc_hir::{Expr, ExprKind};
1313
use rustc_lint::{LateContext, LateLintPass};
1414
use rustc_session::impl_lint_pass;
@@ -43,6 +43,31 @@ declare_clippy_lint! {
4343
"replacing an `Option` with `None` instead of `take()`"
4444
}
4545

46+
declare_clippy_lint! {
47+
/// ### What it does
48+
/// Checks for `mem::replace()` on an `Option` with `Some(…)`.
49+
///
50+
/// ### Why is this bad?
51+
/// `Option` already has the method `replace()` for
52+
/// taking its current value (Some(…) or None) and replacing it with
53+
/// `Some(…)`.
54+
///
55+
/// ### Example
56+
/// ```no_run
57+
/// let mut an_option = Some(0);
58+
/// let replaced = std::mem::replace(&mut an_option, Some(1));
59+
/// ```
60+
/// Is better expressed with:
61+
/// ```no_run
62+
/// let mut an_option = Some(0);
63+
/// let taken = an_option.replace(1);
64+
/// ```
65+
#[clippy::version = "1.86.0"]
66+
pub MEM_REPLACE_OPTION_WITH_SOME,
67+
style,
68+
"replacing an `Option` with `Some` instead of `replace()`"
69+
}
70+
4671
declare_clippy_lint! {
4772
/// ### What it does
4873
/// Checks for `mem::replace(&mut _, mem::uninitialized())`
@@ -101,7 +126,7 @@ declare_clippy_lint! {
101126
}
102127

103128
impl_lint_pass!(MemReplace =>
104-
[MEM_REPLACE_OPTION_WITH_NONE, MEM_REPLACE_WITH_UNINIT, MEM_REPLACE_WITH_DEFAULT]);
129+
[MEM_REPLACE_OPTION_WITH_NONE, MEM_REPLACE_OPTION_WITH_SOME, MEM_REPLACE_WITH_UNINIT, MEM_REPLACE_WITH_DEFAULT]);
105130

106131
fn check_replace_option_with_none(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) -> bool {
107132
if is_res_lang_ctor(cx, path_res(cx, src), OptionNone) {
@@ -130,6 +155,40 @@ fn check_replace_option_with_none(cx: &LateContext<'_>, src: &Expr<'_>, dest: &E
130155
}
131156
}
132157

158+
fn check_replace_option_with_some(
159+
cx: &LateContext<'_>,
160+
src: &Expr<'_>,
161+
dest: &Expr<'_>,
162+
expr_span: Span,
163+
msrv: &Msrv,
164+
) -> bool {
165+
if msrv.meets(msrvs::OPTION_REPLACE)
166+
&& let ExprKind::Call(src_func, [src_arg]) = src.kind
167+
&& is_res_lang_ctor(cx, path_res(cx, src_func), OptionSome)
168+
{
169+
// We do not have to check for a `const` context here, because `core::mem::replace()` and
170+
// `Option::replace()` have been const-stabilized simultaneously in version 1.83.0.
171+
let sugg_expr = peel_ref_operators(cx, dest);
172+
let mut applicability = Applicability::MachineApplicable;
173+
span_lint_and_sugg(
174+
cx,
175+
MEM_REPLACE_OPTION_WITH_SOME,
176+
expr_span,
177+
"replacing an `Option` with `Some(..)`",
178+
"consider `Option::replace()` instead",
179+
format!(
180+
"{}.replace({})",
181+
Sugg::hir_with_context(cx, sugg_expr, expr_span.ctxt(), "_", &mut applicability).maybe_par(),
182+
snippet_with_applicability(cx, src_arg.span, "_", &mut applicability)
183+
),
184+
applicability,
185+
);
186+
true
187+
} else {
188+
false
189+
}
190+
}
191+
133192
fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
134193
if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(src.hir_id)
135194
// check if replacement is mem::MaybeUninit::uninit().assume_init()
@@ -249,6 +308,7 @@ impl<'tcx> LateLintPass<'tcx> for MemReplace {
249308
{
250309
// Check that second argument is `Option::None`
251310
if !check_replace_option_with_none(cx, src, dest, expr.span)
311+
&& !check_replace_option_with_some(cx, src, dest, expr.span, &self.msrv)
252312
&& !check_replace_with_default(cx, src, dest, expr, &self.msrv)
253313
{
254314
check_replace_with_uninit(cx, src, dest, expr.span);

clippy_utils/src/msrvs.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ msrv_aliases! {
5858
1,35,0 { OPTION_COPIED, RANGE_CONTAINS }
5959
1,34,0 { TRY_FROM }
6060
1,33,0 { UNDERSCORE_IMPORTS }
61+
1,31,0 { OPTION_REPLACE }
6162
1,30,0 { ITERATOR_FIND_MAP, TOOL_ATTRIBUTES }
6263
1,29,0 { ITER_FLATTEN }
6364
1,28,0 { FROM_BOOL, REPEAT_WITH }

tests/ui/mem_replace.fixed

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,3 +131,25 @@ fn issue9824() {
131131
// replace with default
132132
let _ = std::mem::take(&mut b.val);
133133
}
134+
135+
#[clippy::msrv = "1.31"]
136+
fn mem_replace_option_with_some() {
137+
let mut an_option = Some(0);
138+
let replaced = an_option.replace(1);
139+
//~^ ERROR: replacing an `Option` with `Some(..)`
140+
141+
let mut an_option = &mut Some(0);
142+
let replaced = an_option.replace(1);
143+
//~^ ERROR: replacing an `Option` with `Some(..)`
144+
145+
let (mut opt1, mut opt2) = (Some(0), Some(0));
146+
let b = true;
147+
let replaced = (if b { &mut opt1 } else { &mut opt2 }).replace(1);
148+
//~^ ERROR: replacing an `Option` with `Some(..)`
149+
}
150+
151+
#[clippy::msrv = "1.30"]
152+
fn mem_replace_option_with_some_bad_msrv() {
153+
let mut an_option = Some(0);
154+
let replaced = mem::replace(&mut an_option, Some(1));
155+
}

tests/ui/mem_replace.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,3 +131,25 @@ fn issue9824() {
131131
// replace with default
132132
let _ = std::mem::replace(&mut b.val, String::default());
133133
}
134+
135+
#[clippy::msrv = "1.31"]
136+
fn mem_replace_option_with_some() {
137+
let mut an_option = Some(0);
138+
let replaced = mem::replace(&mut an_option, Some(1));
139+
//~^ ERROR: replacing an `Option` with `Some(..)`
140+
141+
let mut an_option = &mut Some(0);
142+
let replaced = mem::replace(an_option, Some(1));
143+
//~^ ERROR: replacing an `Option` with `Some(..)`
144+
145+
let (mut opt1, mut opt2) = (Some(0), Some(0));
146+
let b = true;
147+
let replaced = mem::replace(if b { &mut opt1 } else { &mut opt2 }, Some(1));
148+
//~^ ERROR: replacing an `Option` with `Some(..)`
149+
}
150+
151+
#[clippy::msrv = "1.30"]
152+
fn mem_replace_option_with_some_bad_msrv() {
153+
let mut an_option = Some(0);
154+
let replaced = mem::replace(&mut an_option, Some(1));
155+
}

tests/ui/mem_replace.stderr

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,5 +160,26 @@ error: replacing a value of type `T` with `T::default()` is better expressed usi
160160
LL | let _ = std::mem::replace(&mut b.val, String::default());
161161
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `std::mem::take(&mut b.val)`
162162

163-
error: aborting due to 26 previous errors
163+
error: replacing an `Option` with `Some(..)`
164+
--> tests/ui/mem_replace.rs:138:20
165+
|
166+
LL | let replaced = mem::replace(&mut an_option, Some(1));
167+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider `Option::replace()` instead: `an_option.replace(1)`
168+
|
169+
= note: `-D clippy::mem-replace-option-with-some` implied by `-D warnings`
170+
= help: to override `-D warnings` add `#[allow(clippy::mem_replace_option_with_some)]`
171+
172+
error: replacing an `Option` with `Some(..)`
173+
--> tests/ui/mem_replace.rs:142:20
174+
|
175+
LL | let replaced = mem::replace(an_option, Some(1));
176+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider `Option::replace()` instead: `an_option.replace(1)`
177+
178+
error: replacing an `Option` with `Some(..)`
179+
--> tests/ui/mem_replace.rs:147:20
180+
|
181+
LL | let replaced = mem::replace(if b { &mut opt1 } else { &mut opt2 }, Some(1));
182+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider `Option::replace()` instead: `(if b { &mut opt1 } else { &mut opt2 }).replace(1)`
183+
184+
error: aborting due to 29 previous errors
164185

0 commit comments

Comments
 (0)