From 49ec909ca7d649d73115f7e0e894b0ffb0740b66 Mon Sep 17 00:00:00 2001 From: David Wood Date: Tue, 26 Apr 2022 11:59:45 +0100 Subject: macros: subdiagnostic derive Add a new derive, `#[derive(SessionSubdiagnostic)]`, which enables deriving structs for labels, notes, helps and suggestions. Signed-off-by: David Wood --- compiler/rustc_errors/src/diagnostic.rs | 14 ++++++++++++++ compiler/rustc_errors/src/diagnostic_builder.rs | 5 +++++ compiler/rustc_errors/src/lib.rs | 4 ++-- 3 files changed, 21 insertions(+), 2 deletions(-) (limited to 'compiler/rustc_errors') diff --git a/compiler/rustc_errors/src/diagnostic.rs b/compiler/rustc_errors/src/diagnostic.rs index 39cb71848eb..83e6a751394 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -78,6 +78,13 @@ impl<'source> Into> for DiagnosticArgValue<'source> { } } +/// Trait implemented by error types. This should not be implemented manually. Instead, use +/// `#[derive(SessionSubdiagnostic)]` -- see [rustc_macros::SessionSubdiagnostic]. +pub trait AddSubdiagnostic { + /// Add a subdiagnostic to an existing diagnostic. + fn add_to_diagnostic(self, diag: &mut Diagnostic); +} + #[must_use] #[derive(Clone, Debug, Encodable, Decodable)] pub struct Diagnostic { @@ -768,6 +775,13 @@ impl Diagnostic { self } + /// Add a subdiagnostic from a type that implements `SessionSubdiagnostic` - see + /// [rustc_macros::SessionSubdiagnostic]. + pub fn subdiagnostic(&mut self, subdiagnostic: impl AddSubdiagnostic) -> &mut Self { + subdiagnostic.add_to_diagnostic(self); + self + } + pub fn set_span>(&mut self, sp: S) -> &mut Self { self.span = sp.into(); if let Some(span) = self.span.primary_span() { diff --git a/compiler/rustc_errors/src/diagnostic_builder.rs b/compiler/rustc_errors/src/diagnostic_builder.rs index efc7693459f..96b730c2baa 100644 --- a/compiler/rustc_errors/src/diagnostic_builder.rs +++ b/compiler/rustc_errors/src/diagnostic_builder.rs @@ -530,6 +530,11 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> { name: impl Into>, arg: DiagnosticArgValue<'static>, ) -> &mut Self); + + forward!(pub fn subdiagnostic( + &mut self, + subdiagnostic: impl crate::AddSubdiagnostic + ) -> &mut Self); } impl Debug for DiagnosticBuilder<'_, G> { diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index a64133bb7f4..df41fc00714 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -370,8 +370,8 @@ impl fmt::Display for ExplicitBug { impl error::Error for ExplicitBug {} pub use diagnostic::{ - Diagnostic, DiagnosticArg, DiagnosticArgValue, DiagnosticId, DiagnosticStyledString, - IntoDiagnosticArg, SubDiagnostic, + AddSubdiagnostic, Diagnostic, DiagnosticArg, DiagnosticArgValue, DiagnosticId, + DiagnosticStyledString, IntoDiagnosticArg, SubDiagnostic, }; pub use diagnostic_builder::{DiagnosticBuilder, EmissionGuarantee}; use std::backtrace::Backtrace; -- cgit 1.4.1-3-g733a5