Skip to content

Commit a89614d

Browse files
committed
Add suggestion to .to_owned() used on Cow when borrowing
1 parent e1b9081 commit a89614d

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3411,6 +3411,24 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
34113411
Applicability::MaybeIncorrect,
34123412
);
34133413
}
3414+
3415+
if let Some(cow) = tcx.get_diagnostic_item(sym::Cow)
3416+
&& let ty::Adt(adtdef, _) = return_ty.kind()
3417+
&& adtdef.did() == cow
3418+
{
3419+
if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(return_span) {
3420+
if let Some(pos) = snippet.rfind(".to_owned") {
3421+
let byte_pos = BytePos(pos as u32 + 1u32);
3422+
let to_owned_span = return_span.with_hi(return_span.lo() + byte_pos);
3423+
err.span_suggestion_short(
3424+
to_owned_span.shrink_to_hi(),
3425+
"try using `.into_owned()` if you meant to convert a `Cow<'_, T>` to an owned `T`",
3426+
"in",
3427+
Applicability::MaybeIncorrect,
3428+
);
3429+
}
3430+
}
3431+
}
34143432
}
34153433

34163434
Err(err)

tests/ui/issues/cow-to-owned.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// issue #144792
2+
3+
fn main() {
4+
_ = std::env::var_os("RUST_LOG").map_or("warn".into(), |x| x.to_string_lossy().to_owned());
5+
//~^ ERROR cannot return value referencing function parameter
6+
//~| HELP try using `.into_owned()`
7+
}

tests/ui/issues/cow-to-owned.stderr

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
error[E0515]: cannot return value referencing function parameter `x`
2+
--> $DIR/cow-to-owned.rs:4:64
3+
|
4+
LL | _ = std::env::var_os("RUST_LOG").map_or("warn".into(), |x| x.to_string_lossy().to_owned());
5+
| -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6+
| |
7+
| returns a value referencing data owned by the current function
8+
| `x` is borrowed here
9+
|
10+
help: try using `.into_owned()` if you meant to convert a `Cow<'_, T>` to an owned `T`
11+
|
12+
LL | _ = std::env::var_os("RUST_LOG").map_or("warn".into(), |x| x.to_string_lossy().into_owned());
13+
| ++
14+
15+
error: aborting due to 1 previous error
16+
17+
For more information about this error, try `rustc --explain E0515`.

0 commit comments

Comments
 (0)