Avoid misleading closure return type note

This commit is contained in:
yukang
2026-04-27 18:57:50 +08:00
parent 4933094f25
commit 7616881793
3 changed files with 43 additions and 6 deletions
+6 -5
View File
@@ -1998,9 +1998,13 @@ fn report_return_mismatched_types<'infcx>(
);
}
let ret_coercion_span = fcx.ret_coercion_span.get();
let is_return_position = fcx
.tcx
.hir_get_fn_id_for_return_block(block_or_return_id)
.is_some_and(|fn_id| fn_id == fcx.tcx.local_def_id_to_hir_id(fcx.body_id));
if let Some(sp) = ret_coercion_span
if is_return_position
&& let Some(sp) = fcx.ret_coercion_span.get()
// If the closure has an explicit return type annotation, or if
// the closure's return type has been inferred from outside
// requirements (such as an Fn* trait bound), then a type error
@@ -2009,9 +2013,6 @@ fn report_return_mismatched_types<'infcx>(
// note in this case, since it would be incorrect.
&& let Some(fn_sig) = fcx.body_fn_sig()
&& fn_sig.output().is_ty_var()
&& fcx.ret_coercion.as_ref().is_some_and(|ret_coercion| {
fcx.resolve_vars_if_possible(ret_coercion.borrow().expected_ty()) == expected
})
{
err.span_note(sp, format!("return type inferred to be `{expected}` here"));
}
@@ -11,4 +11,28 @@
};
};
const _: fn() -> SmolStr = || {
match Some(()) {
Some(()) => (),
None => return SmolStr,
};
let _: String = {
SmolStr
//~^ ERROR mismatched types
};
SmolStr
};
const _: fn() -> String = || {
match Some(()) {
Some(()) => (),
None => return String::new(),
};
let _: String = {
SmolStr
//~^ ERROR mismatched types
};
String::new()
};
fn main() {}
@@ -4,6 +4,18 @@ error[E0308]: mismatched types
LL | SmolStr
| ^^^^^^^ expected `String`, found `SmolStr`
error: aborting due to 1 previous error
error[E0308]: mismatched types
--> $DIR/closure-return-block-note-issue-155670.rs:20:9
|
LL | SmolStr
| ^^^^^^^ expected `String`, found `SmolStr`
error[E0308]: mismatched types
--> $DIR/closure-return-block-note-issue-155670.rs:32:9
|
LL | SmolStr
| ^^^^^^^ expected `String`, found `SmolStr`
error: aborting due to 3 previous errors
For more information about this error, try `rustc --explain E0308`.