Skip to content

Commit 4129f5c

Browse files
authored
New lint: mem_replace_option_with_some (rust-lang#14197)
`mem::replace(opt, Some(v))` can be replaced by `opt.replace(v)`. Close rust-lang#14195 changelog: [`mem_replace_option_with_some`]: new lint
2 parents 1cb4236 + 342ac8e commit 4129f5c

File tree

9 files changed

+183
-39
lines changed

9 files changed

+183
-39
lines changed

CHANGELOG.md

+1
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

+1
Original file line numberDiff line numberDiff line change
@@ -784,6 +784,7 @@ The minimum rust version that the project supports. Defaults to the `rust-versio
784784
* [`map_unwrap_or`](https://rust-lang.github.io/rust-clippy/master/index.html#map_unwrap_or)
785785
* [`map_with_unused_argument_over_ranges`](https://rust-lang.github.io/rust-clippy/master/index.html#map_with_unused_argument_over_ranges)
786786
* [`match_like_matches_macro`](https://rust-lang.github.io/rust-clippy/master/index.html#match_like_matches_macro)
787+
* [`mem_replace_option_with_some`](https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_option_with_some)
787788
* [`mem_replace_with_default`](https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_with_default)
788789
* [`missing_const_for_fn`](https://rust-lang.github.io/rust-clippy/master/index.html#missing_const_for_fn)
789790
* [`needless_borrow`](https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow)

clippy_config/src/conf.rs

+1
Original file line numberDiff line numberDiff line change
@@ -639,6 +639,7 @@ define_Conf! {
639639
map_unwrap_or,
640640
map_with_unused_argument_over_ranges,
641641
match_like_matches_macro,
642+
mem_replace_option_with_some,
642643
mem_replace_with_default,
643644
missing_const_for_fn,
644645
needless_borrow,

clippy_lints/src/declared_lints.rs

+1
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

+112-38
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,28 +126,67 @@ 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]);
130+
131+
fn check_replace_option_with_none(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) -> bool {
132+
if is_res_lang_ctor(cx, path_res(cx, src), OptionNone) {
133+
// Since this is a late pass (already type-checked),
134+
// and we already know that the second argument is an
135+
// `Option`, we do not need to check the first
136+
// argument's type. All that's left is to get
137+
// the replacee's expr after peeling off the `&mut`
138+
let sugg_expr = peel_ref_operators(cx, dest);
139+
let mut applicability = Applicability::MachineApplicable;
140+
span_lint_and_sugg(
141+
cx,
142+
MEM_REPLACE_OPTION_WITH_NONE,
143+
expr_span,
144+
"replacing an `Option` with `None`",
145+
"consider `Option::take()` instead",
146+
format!(
147+
"{}.take()",
148+
Sugg::hir_with_context(cx, sugg_expr, expr_span.ctxt(), "", &mut applicability).maybe_par()
149+
),
150+
applicability,
151+
);
152+
true
153+
} else {
154+
false
155+
}
156+
}
105157

106-
fn check_replace_option_with_none(cx: &LateContext<'_>, dest: &Expr<'_>, expr_span: Span) {
107-
// Since this is a late pass (already type-checked),
108-
// and we already know that the second argument is an
109-
// `Option`, we do not need to check the first
110-
// argument's type. All that's left is to get
111-
// the replacee's expr after peeling off the `&mut`
112-
let sugg_expr = peel_ref_operators(cx, dest);
113-
let mut applicability = Applicability::MachineApplicable;
114-
span_lint_and_sugg(
115-
cx,
116-
MEM_REPLACE_OPTION_WITH_NONE,
117-
expr_span,
118-
"replacing an `Option` with `None`",
119-
"consider `Option::take()` instead",
120-
format!(
121-
"{}.take()",
122-
Sugg::hir_with_context(cx, sugg_expr, expr_span.ctxt(), "", &mut applicability).maybe_par()
123-
),
124-
applicability,
125-
);
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+
}
126190
}
127191

128192
fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
@@ -181,34 +245,44 @@ fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'
181245
}
182246
}
183247

184-
fn check_replace_with_default(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) {
185-
// disable lint for primitives
186-
let expr_type = cx.typeck_results().expr_ty_adjusted(src);
187-
if is_non_aggregate_primitive_type(expr_type) {
188-
return;
189-
}
190-
if is_default_equivalent(cx, src) && !expr_span.in_external_macro(cx.tcx.sess.source_map()) {
191-
let Some(top_crate) = std_or_core(cx) else { return };
248+
fn check_replace_with_default(
249+
cx: &LateContext<'_>,
250+
src: &Expr<'_>,
251+
dest: &Expr<'_>,
252+
expr: &Expr<'_>,
253+
msrv: &Msrv,
254+
) -> bool {
255+
if msrv.meets(msrvs::MEM_TAKE) && is_expr_used_or_unified(cx.tcx, expr)
256+
// disable lint for primitives
257+
&& let expr_type = cx.typeck_results().expr_ty_adjusted(src)
258+
&& !is_non_aggregate_primitive_type(expr_type)
259+
&& is_default_equivalent(cx, src)
260+
&& !expr.span.in_external_macro(cx.tcx.sess.source_map())
261+
&& let Some(top_crate) = std_or_core(cx)
262+
{
192263
span_lint_and_then(
193264
cx,
194265
MEM_REPLACE_WITH_DEFAULT,
195-
expr_span,
266+
expr.span,
196267
format!(
197268
"replacing a value of type `T` with `T::default()` is better expressed using `{top_crate}::mem::take`"
198269
),
199270
|diag| {
200-
if !expr_span.from_expansion() {
271+
if !expr.span.from_expansion() {
201272
let suggestion = format!("{top_crate}::mem::take({})", snippet(cx, dest.span, ""));
202273

203274
diag.span_suggestion(
204-
expr_span,
275+
expr.span,
205276
"consider using",
206277
suggestion,
207278
Applicability::MachineApplicable,
208279
);
209280
}
210281
},
211282
);
283+
true
284+
} else {
285+
false
212286
}
213287
}
214288

@@ -233,12 +307,12 @@ impl<'tcx> LateLintPass<'tcx> for MemReplace {
233307
&& cx.tcx.is_diagnostic_item(sym::mem_replace, def_id)
234308
{
235309
// Check that second argument is `Option::None`
236-
if is_res_lang_ctor(cx, path_res(cx, src), OptionNone) {
237-
check_replace_option_with_none(cx, dest, expr.span);
238-
} else if self.msrv.meets(msrvs::MEM_TAKE) && is_expr_used_or_unified(cx.tcx, expr) {
239-
check_replace_with_default(cx, src, dest, expr.span);
310+
if !check_replace_option_with_none(cx, src, dest, expr.span)
311+
&& !check_replace_option_with_some(cx, src, dest, expr.span, &self.msrv)
312+
&& !check_replace_with_default(cx, src, dest, expr, &self.msrv)
313+
{
314+
check_replace_with_uninit(cx, src, dest, expr.span);
240315
}
241-
check_replace_with_uninit(cx, src, dest, expr.span);
242316
}
243317
}
244318
extract_msrv_attr!(LateContext);

clippy_utils/src/msrvs.rs

+1
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

+22
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

+22
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

+22-1
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)