Auto merge of #12051 - y21:option_as_ref_cloned, r=dswij

new lint: `option_as_ref_cloned`

Closes #12009

Adds a new lint that looks for `.as_ref().cloned()` on `Option`s. That's the same as just `.clone()`-ing the option directly.

changelog: new lint: [`option_as_ref_cloned`]
This commit is contained in:
bors 2024-01-05 06:39:46 +00:00
commit ee8bfb7f7a
9 changed files with 138 additions and 3 deletions

View file

@ -0,0 +1,21 @@
#![warn(clippy::option_as_ref_cloned)]
#![allow(clippy::clone_on_copy)]
fn main() {
let mut x = Some(String::new());
let _: Option<String> = x.clone();
let _: Option<String> = x.clone();
let y = x.as_ref();
let _: Option<&String> = y.clone();
macro_rules! cloned_recv {
() => {
x.as_ref()
};
}
// Don't lint when part of the expression is from a macro
let _: Option<String> = cloned_recv!().cloned();
}

View file

@ -0,0 +1,21 @@
#![warn(clippy::option_as_ref_cloned)]
#![allow(clippy::clone_on_copy)]
fn main() {
let mut x = Some(String::new());
let _: Option<String> = x.as_ref().cloned();
let _: Option<String> = x.as_mut().cloned();
let y = x.as_ref();
let _: Option<&String> = y.as_ref().cloned();
macro_rules! cloned_recv {
() => {
x.as_ref()
};
}
// Don't lint when part of the expression is from a macro
let _: Option<String> = cloned_recv!().cloned();
}

View file

@ -0,0 +1,37 @@
error: cloning an `Option<_>` using `.as_ref().cloned()`
--> $DIR/option_as_ref_cloned.rs:7:31
|
LL | let _: Option<String> = x.as_ref().cloned();
| ^^^^^^^^^^^^^^^
|
= note: `-D clippy::option-as-ref-cloned` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(clippy::option_as_ref_cloned)]`
help: this can be written more concisely by cloning the `Option<_>` directly
|
LL | let _: Option<String> = x.clone();
| ~~~~~
error: cloning an `Option<_>` using `.as_mut().cloned()`
--> $DIR/option_as_ref_cloned.rs:8:31
|
LL | let _: Option<String> = x.as_mut().cloned();
| ^^^^^^^^^^^^^^^
|
help: this can be written more concisely by cloning the `Option<_>` directly
|
LL | let _: Option<String> = x.clone();
| ~~~~~
error: cloning an `Option<_>` using `.as_ref().cloned()`
--> $DIR/option_as_ref_cloned.rs:11:32
|
LL | let _: Option<&String> = y.as_ref().cloned();
| ^^^^^^^^^^^^^^^
|
help: this can be written more concisely by cloning the `Option<_>` directly
|
LL | let _: Option<&String> = y.clone();
| ~~~~~
error: aborting due to 3 previous errors