@@ -71,6 +71,7 @@ mod no_effect_replace;
7171mod obfuscated_if_else;
7272mod ok_expect;
7373mod open_options;
74+ mod option_as_ref_cloned;
7475mod option_as_ref_deref;
7576mod option_map_or_err_ok;
7677mod option_map_or_none;
@@ -3887,6 +3888,31 @@ declare_clippy_lint! {
38873888 "splitting a trimmed string at hard-coded newlines"
38883889}
38893890
3891+ declare_clippy_lint ! {
3892+ /// ### What it does
3893+ /// Checks for usage of `.as_ref().cloned()` and `.as_mut().cloned()` on `Option`s
3894+ ///
3895+ /// ### Why is this bad?
3896+ /// This can be written more concisely by cloning the `Option` directly.
3897+ ///
3898+ /// ### Example
3899+ /// ```no_run
3900+ /// fn foo(bar: &Option<Vec<u8>>) -> Option<Vec<u8>> {
3901+ /// bar.as_ref().cloned()
3902+ /// }
3903+ /// ```
3904+ /// Use instead:
3905+ /// ```no_run
3906+ /// fn foo(bar: &Option<Vec<u8>>) -> Option<Vec<u8>> {
3907+ /// bar.clone()
3908+ /// }
3909+ /// ```
3910+ #[ clippy:: version = "1.77.0" ]
3911+ pub OPTION_AS_REF_CLONED ,
3912+ pedantic,
3913+ "cloning an `Option` via `as_ref().cloned()`"
3914+ }
3915+
38903916pub struct Methods {
38913917 avoid_breaking_exported_api : bool ,
38923918 msrv : Msrv ,
@@ -4043,6 +4069,7 @@ impl_lint_pass!(Methods => [
40434069 ITER_FILTER_IS_OK ,
40444070 MANUAL_IS_VARIANT_AND ,
40454071 STR_SPLIT_AT_NEWLINE ,
4072+ OPTION_AS_REF_CLONED ,
40464073] ) ;
40474074
40484075/// Extracts a method call name, args, and `Span` of the method name.
@@ -4290,7 +4317,10 @@ impl Methods {
42904317 ( "as_mut" , [ ] ) => useless_asref:: check ( cx, expr, "as_mut" , recv) ,
42914318 ( "as_ref" , [ ] ) => useless_asref:: check ( cx, expr, "as_ref" , recv) ,
42924319 ( "assume_init" , [ ] ) => uninit_assumed_init:: check ( cx, expr, recv) ,
4293- ( "cloned" , [ ] ) => cloned_instead_of_copied:: check ( cx, expr, recv, span, & self . msrv ) ,
4320+ ( "cloned" , [ ] ) => {
4321+ cloned_instead_of_copied:: check ( cx, expr, recv, span, & self . msrv ) ;
4322+ option_as_ref_cloned:: check ( cx, recv, span) ;
4323+ } ,
42944324 ( "collect" , [ ] ) if is_trait_method ( cx, expr, sym:: Iterator ) => {
42954325 needless_collect:: check ( cx, span, expr, recv, call_span) ;
42964326 match method_call ( recv) {
0 commit comments