Print note with closure signature on type mismatch

This commit is contained in:
Daniel Sedlak 2024-04-02 19:53:13 +02:00
parent 13e63f7490
commit be564a8add
4 changed files with 48 additions and 2 deletions

View file

@ -730,7 +730,7 @@ pub fn note(&mut self, msg: impl Into<SubdiagMessage>) -> &mut Self {
} }
#[rustc_lint_diagnostics]
fn highlighted_note(&mut self, msg: Vec<StringPart>) -> &mut Self {
pub fn highlighted_note(&mut self, msg: Vec<StringPart>) -> &mut Self {
self.sub_with_highlights(Level::Note, msg, MultiSpan::new());
self
}

View file

@ -61,7 +61,7 @@
use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
use rustc_errors::{
codes::*, pluralize, struct_span_code_err, Applicability, Diag, DiagCtxt, DiagStyledString,
ErrorGuaranteed, IntoDiagArg,
ErrorGuaranteed, IntoDiagArg, StringPart,
};
use rustc_hir as hir;
use rustc_hir::def::DefKind;
@ -1917,6 +1917,23 @@ enum Similar<'tcx> {
);
if !is_simple_error || terr.must_include_note() {
diag.note_expected_found(&expected_label, expected, &found_label, found);
if let Some(ty::Closure(_, args)) =
exp_found.map(|expected_type_found| expected_type_found.found.kind())
{
diag.highlighted_note(vec![
StringPart::normal("closure has signature: `"),
StringPart::highlighted(
self.tcx
.signature_unclosure(
args.as_closure().sig(),
rustc_hir::Unsafety::Normal,
)
.to_string(),
),
StringPart::normal("`"),
]);
}
}
}
}

View file

@ -0,0 +1,11 @@
fn main() {
let x = |a: u8, b: (usize, u32), c: fn() -> char| -> String { "I love beans.".to_string() };
//~^ NOTE: the found closure
let x: fn(i32) = x;
//~^ ERROR: 5:22: 5:23: mismatched types [E0308]
//~| NOTE: incorrect number of function parameters
//~| NOTE: expected due to this
//~| NOTE: expected fn pointer `fn(i32)`
//~| NOTE: closure has signature: `fn(u8, (usize, u32), fn() -> char) -> String`
}

View file

@ -0,0 +1,18 @@
error[E0308]: mismatched types
--> $DIR/hint-closure-signature-119266.rs:5:22
|
LL | let x = |a: u8, b: (usize, u32), c: fn() -> char| -> String { "I love beans.".to_string() };
| --------------------------------------------------- the found closure
...
LL | let x: fn(i32) = x;
| ------- ^ incorrect number of function parameters
| |
| expected due to this
|
= note: expected fn pointer `fn(i32)`
found closure `{closure@$DIR/hint-closure-signature-119266.rs:2:13: 2:64}`
= note: closure has signature: `fn(u8, (usize, u32), fn() -> char) -> String`
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0308`.