Skip to content

Commit f1f1c9b

Browse files
Improve errors for missing Debug and Display impls
1 parent 0a8629b commit f1f1c9b

File tree

3 files changed

+27
-1
lines changed
  • compiler
    • rustc_span/src
    • rustc_trait_selection/src/traits/error_reporting
  • library/core/src/fmt

3 files changed

+27
-1
lines changed

compiler/rustc_span/src/symbol.rs

+1
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,7 @@ symbols! {
479479
discriminant_type,
480480
discriminant_value,
481481
dispatch_from_dyn,
482+
display_trait,
482483
div,
483484
div_assign,
484485
doc,

compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs

+24
Original file line numberDiff line numberDiff line change
@@ -514,6 +514,30 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
514514
}
515515
}
516516

517+
// Return early if the trait is Debug or Display and the invocation
518+
// originates within a standard library macro, because the output
519+
// is otherwise overwhelming and unhelpful (see #85844 for an
520+
// example).
521+
522+
let trait_is_debug =
523+
self.tcx.is_diagnostic_item(sym::debug_trait, trait_ref.def_id());
524+
let trait_is_display =
525+
self.tcx.is_diagnostic_item(sym::display_trait, trait_ref.def_id());
526+
527+
let in_std_macro =
528+
match obligation.cause.span.ctxt().outer_expn_data().macro_def_id {
529+
Some(macro_def_id) => {
530+
let crate_name = tcx.crate_name(macro_def_id.krate);
531+
crate_name == sym::std || crate_name == sym::core
532+
}
533+
None => false,
534+
};
535+
536+
if in_std_macro && (trait_is_debug || trait_is_display) {
537+
err.emit();
538+
return;
539+
}
540+
517541
err
518542
}
519543

library/core/src/fmt/mod.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -564,7 +564,7 @@ impl Display for Arguments<'_> {
564564
on(
565565
crate_local,
566566
label = "`{Self}` cannot be formatted using `{{:?}}`",
567-
note = "add `#[derive(Debug)]` or manually implement `{Debug}`"
567+
note = "add `#[derive(Debug)]` to `{Self}` or manually implement `{Debug}` for `{Self}`"
568568
),
569569
message = "`{Self}` doesn't implement `{Debug}`",
570570
label = "`{Self}` cannot be formatted using `{{:?}}` because it doesn't implement `{Debug}`"
@@ -662,6 +662,7 @@ pub use macros::Debug;
662662
note = "in format strings you may be able to use `{{:?}}` (or {{:#?}} for pretty-print) instead"
663663
)]
664664
#[doc(alias = "{}")]
665+
#[rustc_diagnostic_item = "display_trait"]
665666
#[stable(feature = "rust1", since = "1.0.0")]
666667
pub trait Display {
667668
/// Formats the value using the given formatter.

0 commit comments

Comments
 (0)