diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index 2bbf90ed3ed1..a81f7574c5e5 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -1195,6 +1195,15 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { c @ ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, _) if self.tcx.hir_span(*hir_id).lo() == span.lo() => { + if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(*hir_id) + && let hir::ExprKind::Call(base, _) = expr.kind + && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, _)) = base.kind + && ty.span == span + { + // Do not suggest borrowing when we already do so. This would happen with + // `let _ = &str::from("");` where the expression corresponds to the `str`. + return false; + } c } c if matches!( diff --git a/tests/ui/suggestions/dont-suggest-borrowing-existing-borrow.rs b/tests/ui/suggestions/dont-suggest-borrowing-existing-borrow.rs new file mode 100644 index 000000000000..c25bde5d0a23 --- /dev/null +++ b/tests/ui/suggestions/dont-suggest-borrowing-existing-borrow.rs @@ -0,0 +1,5 @@ +fn main() { + let _ = &str::from("value"); + //~^ ERROR the trait bound `str: From<_>` is not satisfied + //~| ERROR the size for values of type `str` cannot be known at compilation time +} diff --git a/tests/ui/suggestions/dont-suggest-borrowing-existing-borrow.stderr b/tests/ui/suggestions/dont-suggest-borrowing-existing-borrow.stderr new file mode 100644 index 000000000000..025014aa0229 --- /dev/null +++ b/tests/ui/suggestions/dont-suggest-borrowing-existing-borrow.stderr @@ -0,0 +1,26 @@ +error[E0277]: the trait bound `str: From<_>` is not satisfied + --> $DIR/dont-suggest-borrowing-existing-borrow.rs:2:14 + | +LL | let _ = &str::from("value"); + | ^^^ the trait `From<_>` is not implemented for `str` + | + = help: the following other types implement trait `From`: + `String` implements `From<&String>` + `String` implements `From<&mut str>` + `String` implements `From<&str>` + `String` implements `From>` + `String` implements `From>` + `String` implements `From` + +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> $DIR/dont-suggest-borrowing-existing-borrow.rs:2:14 + | +LL | let _ = &str::from("value"); + | ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `str` + = note: the return type of a function must have a statically known size + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0277`.