From d5bddeee29f2b09c3cd14feaf8ad057fb94da2e4 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sat, 29 Jun 2024 14:49:27 -0400 Subject: [PATCH] Use full expr span for return suggestion on type error/ambiguity --- .../rustc_hir_typeck/src/fn_ctxt/checks.rs | 3 ++- .../return/tail-expr-as-potential-return.rs | 16 +++++++++++++++ .../tail-expr-as-potential-return.stderr | 20 +++++++++++++++++-- 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index 1138642c56d61..f4f3f24316716 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -2042,7 +2042,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } if block_num > 1 && found_semi { err.span_suggestion_verbose( - span.shrink_to_lo(), + // use the span of the *whole* expr + self.tcx.hir().span(binding_hir_id).shrink_to_lo(), "you might have meant to return this to infer its type parameters", "return ", Applicability::MaybeIncorrect, diff --git a/tests/ui/return/tail-expr-as-potential-return.rs b/tests/ui/return/tail-expr-as-potential-return.rs index 37dee1c19db8c..c753e92a447ff 100644 --- a/tests/ui/return/tail-expr-as-potential-return.rs +++ b/tests/ui/return/tail-expr-as-potential-return.rs @@ -45,3 +45,19 @@ async fn foo2() -> i32 { } 0 } + +struct Receiver; +impl Receiver { + fn generic(self) -> Option { + None + } +} +fn method() -> Option { + if true { + Receiver.generic(); + //~^ ERROR type annotations needed + //| HELP you might have meant to return this value + } + + None +} diff --git a/tests/ui/return/tail-expr-as-potential-return.stderr b/tests/ui/return/tail-expr-as-potential-return.stderr index ccb208fc6c4ae..c0b7d38e18f41 100644 --- a/tests/ui/return/tail-expr-as-potential-return.stderr +++ b/tests/ui/return/tail-expr-as-potential-return.stderr @@ -47,6 +47,22 @@ help: you might have meant to return this value LL | return Err(42); | ++++++ + -error: aborting due to 3 previous errors +error[E0282]: type annotations needed + --> $DIR/tail-expr-as-potential-return.rs:57:18 + | +LL | Receiver.generic(); + | ^^^^^^^ cannot infer type of the type parameter `T` declared on the method `generic` + | +help: consider specifying the generic argument + | +LL | Receiver.generic::(); + | +++++ +help: you might have meant to return this to infer its type parameters + | +LL | return Receiver.generic(); + | ++++++ + +error: aborting due to 4 previous errors -For more information about this error, try `rustc --explain E0308`. +Some errors have detailed explanations: E0282, E0308. +For more information about an error, try `rustc --explain E0282`.