From 3403c4fec70f77f67426fc47a85d14f0935c9dc8 Mon Sep 17 00:00:00 2001 From: Anne Stijns Date: Sun, 3 Aug 2025 21:57:44 +0200 Subject: [PATCH] Add suggestion to `.to_owned()` used on `Cow` when borrowing --- .../src/diagnostics/conflict_errors.rs | 18 ++++++++++++++++++ tests/ui/errors/cow-to-owned.rs | 7 +++++++ tests/ui/errors/cow-to-owned.stderr | 17 +++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 tests/ui/errors/cow-to-owned.rs create mode 100644 tests/ui/errors/cow-to-owned.stderr diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index be8b3f0bc1e39..efc032bdebf26 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -3411,6 +3411,24 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { Applicability::MaybeIncorrect, ); } + + if let Some(cow) = tcx.get_diagnostic_item(sym::Cow) + && let ty::Adt(adtdef, _) = return_ty.kind() + && adtdef.did() == cow + { + if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(return_span) { + if let Some(pos) = snippet.rfind(".to_owned") { + let byte_pos = BytePos(pos as u32 + 1u32); + let to_owned_span = return_span.with_hi(return_span.lo() + byte_pos); + err.span_suggestion_short( + to_owned_span.shrink_to_hi(), + "try using `.into_owned()` if you meant to convert a `Cow<'_, T>` to an owned `T`", + "in", + Applicability::MaybeIncorrect, + ); + } + } + } } Err(err) diff --git a/tests/ui/errors/cow-to-owned.rs b/tests/ui/errors/cow-to-owned.rs new file mode 100644 index 0000000000000..03e828bf3ebf9 --- /dev/null +++ b/tests/ui/errors/cow-to-owned.rs @@ -0,0 +1,7 @@ +// issue #144792 + +fn main() { + _ = std::env::var_os("RUST_LOG").map_or("warn".into(), |x| x.to_string_lossy().to_owned()); + //~^ ERROR cannot return value referencing function parameter + //~| HELP try using `.into_owned()` +} diff --git a/tests/ui/errors/cow-to-owned.stderr b/tests/ui/errors/cow-to-owned.stderr new file mode 100644 index 0000000000000..02bcebd4faf5e --- /dev/null +++ b/tests/ui/errors/cow-to-owned.stderr @@ -0,0 +1,17 @@ +error[E0515]: cannot return value referencing function parameter `x` + --> $DIR/cow-to-owned.rs:4:64 + | +LL | _ = std::env::var_os("RUST_LOG").map_or("warn".into(), |x| x.to_string_lossy().to_owned()); + | -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | returns a value referencing data owned by the current function + | `x` is borrowed here + | +help: try using `.into_owned()` if you meant to convert a `Cow<'_, T>` to an owned `T` + | +LL | _ = std::env::var_os("RUST_LOG").map_or("warn".into(), |x| x.to_string_lossy().into_owned()); + | ++ + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0515`.