Skip to content

Commit beee9e7

Browse files
Periodic1911m4rch3n1ng
authored andcommitted
Add suggestion to .to_owned() used on Cow when borrowing
1 parent e4fdb55 commit beee9e7

3 files changed

Lines changed: 42 additions & 0 deletions

File tree

compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3530,6 +3530,24 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
35303530
Applicability::MaybeIncorrect,
35313531
);
35323532
}
3533+
3534+
if let Some(cow) = tcx.get_diagnostic_item(sym::Cow)
3535+
&& let ty::Adt(adtdef, _) = return_ty.kind()
3536+
&& adtdef.did() == cow
3537+
{
3538+
if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(return_span) {
3539+
if let Some(pos) = snippet.rfind(".to_owned") {
3540+
let byte_pos = BytePos(pos as u32 + 1u32);
3541+
let to_owned_span = return_span.with_hi(return_span.lo() + byte_pos);
3542+
err.span_suggestion_short(
3543+
to_owned_span.shrink_to_hi(),
3544+
"try using `.into_owned()` if you meant to convert a `Cow<'_, T>` to an owned `T`",
3545+
"in",
3546+
Applicability::MaybeIncorrect,
3547+
);
3548+
}
3549+
}
3550+
}
35333551
}
35343552

35353553
Err(err)

tests/ui/errors/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+
}
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)