Improve errors for missing Debug and Display impls

This commit is contained in:
Aris Merchant 2021-06-13 01:36:53 -07:00
parent 0a8629bff6
commit f1f1c9b25b
3 changed files with 27 additions and 1 deletions

View File

@ -479,6 +479,7 @@ symbols! {
discriminant_type,
discriminant_value,
dispatch_from_dyn,
display_trait,
div,
div_assign,
doc,

View File

@ -514,6 +514,30 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
}
}
// Return early if the trait is Debug or Display and the invocation
// originates within a standard library macro, because the output
// is otherwise overwhelming and unhelpful (see #85844 for an
// example).
let trait_is_debug =
self.tcx.is_diagnostic_item(sym::debug_trait, trait_ref.def_id());
let trait_is_display =
self.tcx.is_diagnostic_item(sym::display_trait, trait_ref.def_id());
let in_std_macro =
match obligation.cause.span.ctxt().outer_expn_data().macro_def_id {
Some(macro_def_id) => {
let crate_name = tcx.crate_name(macro_def_id.krate);
crate_name == sym::std || crate_name == sym::core
}
None => false,
};
if in_std_macro && (trait_is_debug || trait_is_display) {
err.emit();
return;
}
err
}

View File

@ -564,7 +564,7 @@ impl Display for Arguments<'_> {
on(
crate_local,
label = "`{Self}` cannot be formatted using `{{:?}}`",
note = "add `#[derive(Debug)]` or manually implement `{Debug}`"
note = "add `#[derive(Debug)]` to `{Self}` or manually implement `{Debug}` for `{Self}`"
),
message = "`{Self}` doesn't implement `{Debug}`",
label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
@ -662,6 +662,7 @@ pub use macros::Debug;
note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
)]
#[doc(alias = "{}")]
#[rustc_diagnostic_item = "display_trait"]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Display {
/// Formats the value using the given formatter.