Suggest value on bare return

This commit is contained in:
Michael Goulet 2024-04-14 09:35:52 -04:00
parent e4c71f1fd8
commit 4af94cfa05
5 changed files with 42 additions and 0 deletions

View File

@ -63,6 +63,7 @@
use rustc_span::{BytePos, Span};
use rustc_target::spec::abi::Abi;
use rustc_trait_selection::infer::InferCtxtExt as _;
use rustc_trait_selection::traits::error_reporting::suggestions::TypeErrCtxtExt;
use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _;
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
use rustc_trait_selection::traits::TraitEngineExt as _;
@ -1616,6 +1617,15 @@ pub(crate) fn coerce_inner<'a>(
E0069,
"`return;` in a function whose return type is not `()`"
);
if let Some(value) = fcx.err_ctxt().ty_kind_suggestion(fcx.param_env, found)
{
err.span_suggestion_verbose(
cause.span.shrink_to_hi(),
"give the `return` a value of the expected type",
format!(" {value}"),
Applicability::HasPlaceholders,
);
}
err.span_label(cause.span, "return type is not `()`");
}
ObligationCauseCode::BlockTailExpression(blk_id, ..) => {

View File

@ -5,6 +5,11 @@ LL | fn foo() -> u8 {
| -- expected `u8` because of this return type
LL | return;
| ^^^^^^ return type is not `()`
|
help: give the `return` a value of the expected type
|
LL | return 42;
| ++
error: aborting due to 1 previous error

View File

@ -5,6 +5,11 @@ LL | fn g() -> isize { return; }
| ----- ^^^^^^ return type is not `()`
| |
| expected `isize` because of this return type
|
help: give the `return` a value of the expected type
|
LL | fn g() -> isize { return 42; }
| ++
error: aborting due to 1 previous error

View File

@ -0,0 +1,6 @@
fn test() -> (i32,) {
return;
//~^ ERROR `return;` in a function whose return type is not `()`
}
fn main() {}

View File

@ -0,0 +1,16 @@
error[E0069]: `return;` in a function whose return type is not `()`
--> $DIR/suggest-a-value.rs:2:5
|
LL | fn test() -> (i32,) {
| ------ expected `(i32,)` because of this return type
LL | return;
| ^^^^^^ return type is not `()`
|
help: give the `return` a value of the expected type
|
LL | return (42);
| ++++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0069`.