Skip to content

Commit bb74f47

Browse files
committed
Do not suggest borrow that is already there in fully-qualified call
When encountering `&str::from("value")` do not suggest `&&str::from("value")`. Fix #132041.
1 parent 076a0a2 commit bb74f47

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1195,6 +1195,15 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
11951195
c @ ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, _)
11961196
if self.tcx.hir_span(*hir_id).lo() == span.lo() =>
11971197
{
1198+
if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(*hir_id)
1199+
&& let hir::ExprKind::Call(base, _) = expr.kind
1200+
&& let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, _)) = base.kind
1201+
&& ty.span == span
1202+
{
1203+
// Do not suggest borrowing when we already do so. This would happen with
1204+
// `let _ = &str::from("");` where the expression corresponds to the `str`.
1205+
return false;
1206+
}
11981207
c
11991208
}
12001209
c if matches!(
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
fn main() {
2+
let _ = &str::from("value");
3+
//~^ ERROR the trait bound `str: From<_>` is not satisfied
4+
//~| ERROR the size for values of type `str` cannot be known at compilation time
5+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
error[E0277]: the trait bound `str: From<_>` is not satisfied
2+
--> $DIR/dont-suggest-borrowing-existing-borrow.rs:2:14
3+
|
4+
LL | let _ = &str::from("value");
5+
| ^^^ the trait `From<_>` is not implemented for `str`
6+
|
7+
= help: the following other types implement trait `From<T>`:
8+
`String` implements `From<&String>`
9+
`String` implements `From<&mut str>`
10+
`String` implements `From<&str>`
11+
`String` implements `From<Box<str>>`
12+
`String` implements `From<Cow<'_, str>>`
13+
`String` implements `From<char>`
14+
15+
error[E0277]: the size for values of type `str` cannot be known at compilation time
16+
--> $DIR/dont-suggest-borrowing-existing-borrow.rs:2:14
17+
|
18+
LL | let _ = &str::from("value");
19+
| ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
20+
|
21+
= help: the trait `Sized` is not implemented for `str`
22+
= note: the return type of a function must have a statically known size
23+
24+
error: aborting due to 2 previous errors
25+
26+
For more information about this error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)