Skip to main content

runic_diagnostics/
owned.rs

1use alloc::{boxed::Box, string::String, vec::Vec};
2use core::{any::Any, fmt};
3
4use crate::{
5    AnnotateRenderer, Diagnostic, DiagnosticCodeRef, DiagnosticDescriptor, DiagnosticMetadata,
6    DiagnosticTag, LayeredSourceProvider, PreparationLimits, PrepareError, PreparedDiagnostic,
7    RenderConfig, RenderError, Severity, SourceProvider,
8    diagnostic::DiagnosticMessage,
9    emit::render_or_degrade,
10    snapshot::{prepare_owned_ref, prepare_owned_ref_with_limits},
11    source::EMPTY_SOURCE_PROVIDER,
12};
13
14const REPORT_PREPARATION_FALLBACK: &str =
15    "error: diagnostic preparation failed; rich output unavailable";
16
17/// A failure while preparing or rendering one owned diagnostic.
18#[derive(Clone, Debug, Eq, PartialEq)]
19pub enum DiagnosticRenderError {
20    /// Snapshot preparation failed.
21    Prepare(PrepareError),
22    /// Rendering a prepared snapshot failed.
23    Render(RenderError),
24}
25
26impl fmt::Display for DiagnosticRenderError {
27    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
28        match self {
29            Self::Prepare(error) => write!(formatter, "diagnostic preparation failed: {error}"),
30            Self::Render(error) => write!(formatter, "diagnostic rendering failed: {error}"),
31        }
32    }
33}
34
35impl core::error::Error for DiagnosticRenderError {
36    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
37        match self {
38            Self::Prepare(error) => Some(error),
39            Self::Render(error) => Some(error),
40        }
41    }
42}
43
44impl From<PrepareError> for DiagnosticRenderError {
45    fn from(error: PrepareError) -> Self {
46        Self::Prepare(error)
47    }
48}
49
50impl From<RenderError> for DiagnosticRenderError {
51    fn from(error: RenderError) -> Self {
52        Self::Render(error)
53    }
54}
55
56trait ErasedDiagnostic: Diagnostic + Send + Sync + 'static {
57    fn diagnostic(&self) -> &dyn Diagnostic;
58    fn as_any(&self) -> &dyn Any;
59    fn as_any_mut(&mut self) -> &mut dyn Any;
60    fn into_any(self: Box<Self>) -> Box<dyn Any>;
61}
62
63impl<T> ErasedDiagnostic for T
64where
65    T: Diagnostic + Send + Sync + 'static,
66{
67    fn diagnostic(&self) -> &dyn Diagnostic {
68        self
69    }
70
71    fn as_any(&self) -> &dyn Any {
72        self
73    }
74
75    fn as_any_mut(&mut self) -> &mut dyn Any {
76        self
77    }
78
79    fn into_any(self: Box<Self>) -> Box<dyn Any> {
80        self
81    }
82}
83
84/// An owned report context captured as text.
85#[derive(Clone, Debug, Eq, PartialEq)]
86pub struct ContextFrame {
87    message: String,
88}
89
90impl ContextFrame {
91    pub fn new(message: impl Into<String>) -> Self {
92        Self {
93            message: message.into(),
94        }
95    }
96
97    pub fn message(&self) -> &str {
98        &self.message
99    }
100}
101
102/// An owned, transport-safe diagnostic occurrence.
103pub struct OwnedDiagnostic {
104    inner: Box<dyn ErasedDiagnostic>,
105    contexts: Vec<ContextFrame>,
106    severity_override: Option<Severity>,
107    session_sources: Option<Box<dyn SourceProvider + Send + Sync>>,
108    attached_sources: Option<Box<dyn SourceProvider + Send + Sync>>,
109}
110
111impl OwnedDiagnostic {
112    /// Owns a transport-safe diagnostic.
113    ///
114    /// Borrowed or local diagnostics remain usable through direct synchronous
115    /// `Diagnostic::message` and `Diagnostic::visit`, but they cannot cross
116    /// this owned boundary.
117    ///
118    /// ```compile_fail
119    /// extern crate alloc;
120    /// use runic_diagnostics::{Diagnostic, OwnedDiagnostic};
121    /// use core::fmt;
122    ///
123    /// #[derive(Debug)]
124    /// struct Borrowed<'a>(&'a str);
125    /// impl Diagnostic for Borrowed<'_> {
126    ///     fn message(&self, out: &mut dyn fmt::Write) -> fmt::Result {
127    ///         out.write_str(self.0)
128    ///     }
129    /// }
130    ///
131    /// let text = alloc::string::String::from("local");
132    /// let _ = OwnedDiagnostic::new(Borrowed(&text));
133    /// ```
134    ///
135    /// ```compile_fail
136    /// extern crate alloc;
137    /// use alloc::rc::Rc;
138    /// use core::{cell::Cell, fmt};
139    /// use runic_diagnostics::{Diagnostic, OwnedDiagnostic};
140    ///
141    /// #[derive(Debug)]
142    /// struct Local(Rc<Cell<u32>>);
143    /// impl Diagnostic for Local {
144    ///     fn message(&self, out: &mut dyn fmt::Write) -> fmt::Result {
145    ///         write!(out, "{}", self.0.get())
146    ///     }
147    /// }
148    ///
149    /// let _ = OwnedDiagnostic::new(Local(Rc::new(Cell::new(1))));
150    /// ```
151    pub fn new<T>(diagnostic: T) -> Self
152    where
153        T: Diagnostic + Send + Sync + 'static,
154    {
155        Self {
156            inner: Box::new(diagnostic),
157            contexts: Vec::new(),
158            severity_override: None,
159            session_sources: None,
160            attached_sources: None,
161        }
162    }
163
164    pub fn as_diagnostic(&self) -> &dyn Diagnostic {
165        self.inner.diagnostic()
166    }
167
168    pub fn descriptor(&self) -> Option<&'static DiagnosticDescriptor> {
169        self.as_diagnostic().descriptor()
170    }
171
172    pub fn code(&self) -> Option<DiagnosticCodeRef<'_>> {
173        self.as_diagnostic().code()
174    }
175
176    pub fn tags(&self) -> &[DiagnosticTag] {
177        self.as_diagnostic().tags()
178    }
179
180    pub fn severity(&self) -> Severity {
181        self.severity_override.unwrap_or_else(|| self.as_diagnostic().severity())
182    }
183
184    pub const fn severity_override(&self) -> Option<Severity> {
185        self.severity_override
186    }
187
188    pub fn set_severity_override(&mut self, severity: Option<Severity>) {
189        self.severity_override = severity;
190    }
191
192    pub fn with_severity_override(mut self, severity: Severity) -> Self {
193        self.severity_override = Some(severity);
194        self
195    }
196
197    pub fn metadata(&self) -> DiagnosticMetadata<'_> {
198        DiagnosticMetadata {
199            descriptor: self.descriptor(),
200            code: self.code(),
201            severity: self.severity(),
202            tags: self.tags(),
203        }
204    }
205
206    pub fn contexts(&self) -> &[ContextFrame] {
207        &self.contexts
208    }
209
210    pub fn push_context(&mut self, context: impl Into<String>) {
211        self.contexts.push(ContextFrame::new(context));
212    }
213
214    pub fn with_context(mut self, context: impl Into<String>) -> Self {
215        self.push_context(context);
216        self
217    }
218
219    pub fn attach_sources<P>(mut self, sources: P) -> Self
220    where
221        P: SourceProvider + Send + Sync + 'static,
222    {
223        self.attached_sources = Some(Box::new(sources));
224        self
225    }
226
227    /// Retains a session source provider with this diagnostic occurrence.
228    ///
229    /// This is useful when the operation that allocated session source IDs transfers diagnostics
230    /// to a caller without otherwise retaining the operation's source manager. An explicit source
231    /// provider passed to [`Self::prepare`] or [`Self::display_with_sources`] takes precedence.
232    pub fn attach_session_sources<P>(mut self, sources: P) -> Self
233    where
234        P: SourceProvider + Send + Sync + 'static,
235    {
236        self.set_session_sources(sources);
237        self
238    }
239
240    pub fn set_session_sources<P>(&mut self, sources: P)
241    where
242        P: SourceProvider + Send + Sync + 'static,
243    {
244        self.session_sources = Some(Box::new(sources));
245    }
246
247    pub fn session_sources(&self) -> Option<&(dyn SourceProvider + Send + Sync + 'static)> {
248        self.session_sources.as_deref()
249    }
250
251    pub fn attached_sources(&self) -> Option<&(dyn SourceProvider + Send + Sync + 'static)> {
252        self.attached_sources.as_deref()
253    }
254
255    /// Prepares this diagnostic with its occurrence metadata and source universes.
256    ///
257    /// `session_sources` resolves [`crate::SourceKey::Session`] spans. Sources
258    /// attached to this diagnostic continue to resolve
259    /// [`crate::SourceKey::Attached`] spans without fallback between the two
260    /// namespaces.
261    pub fn prepare<'a>(
262        &'a self,
263        session_sources: &'a dyn SourceProvider,
264    ) -> Result<PreparedDiagnostic<'a>, PrepareError> {
265        let snapshot = prepare_owned_ref(self)?;
266        Ok(self.prepared(snapshot, session_sources))
267    }
268
269    /// Prepares this diagnostic with explicit resource limits.
270    pub fn prepare_with_limits<'a>(
271        &'a self,
272        session_sources: &'a dyn SourceProvider,
273        limits: PreparationLimits,
274    ) -> Result<PreparedDiagnostic<'a>, PrepareError> {
275        let snapshot = prepare_owned_ref_with_limits(self, limits)?;
276        Ok(self.prepared(snapshot, session_sources))
277    }
278
279    /// Prepares this diagnostic using only sources attached to it.
280    ///
281    /// Rendering a session span in the returned diagnostic will produce a
282    /// missing-source error.
283    pub fn prepare_attached(&self) -> Result<PreparedDiagnostic<'_>, PrepareError> {
284        let session = self
285            .session_sources()
286            .map_or(&EMPTY_SOURCE_PROVIDER as &dyn SourceProvider, |sources| sources);
287        self.prepare(session)
288    }
289
290    /// Prepares this diagnostic using only attached sources and explicit limits.
291    pub fn prepare_attached_with_limits(
292        &self,
293        limits: PreparationLimits,
294    ) -> Result<PreparedDiagnostic<'_>, PrepareError> {
295        let session = self
296            .session_sources()
297            .map_or(&EMPTY_SOURCE_PROVIDER as &dyn SourceProvider, |sources| sources);
298        self.prepare_with_limits(session, limits)
299    }
300
301    /// Returns a rich-formatting adapter using attached sources and portable defaults.
302    pub fn display(&self) -> DiagnosticDisplay<'_> {
303        let session = self
304            .session_sources()
305            .map_or(&EMPTY_SOURCE_PROVIDER as &dyn SourceProvider, |sources| sources);
306        DiagnosticDisplay::new(self, session)
307    }
308
309    /// Returns a rich-formatting adapter with an explicit session source provider.
310    ///
311    /// Sources attached to this diagnostic are layered with `session_sources`
312    /// and remain scoped to attached spans.
313    pub fn display_with_sources<'a>(
314        &'a self,
315        session_sources: &'a dyn SourceProvider,
316    ) -> DiagnosticDisplay<'a> {
317        DiagnosticDisplay::new(self, session_sources)
318    }
319
320    pub fn is<T: 'static>(&self) -> bool {
321        let any = self.inner.as_any();
322        any.is::<T>() || any.is::<DiagnosticError<T>>()
323    }
324
325    pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
326        if let Some(t) = self.inner.as_any().downcast_ref::<T>() {
327            Some(t)
328        } else {
329            self.inner.as_any().downcast_ref::<DiagnosticError<T>>().map(AsRef::as_ref)
330        }
331    }
332
333    pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
334        let inner = self.inner.as_any_mut();
335        if inner.is::<T>() {
336            inner.downcast_mut()
337        } else {
338            inner.downcast_mut::<DiagnosticError<T>>().map(AsMut::as_mut)
339        }
340    }
341
342    pub fn downcast<T: 'static>(self) -> Result<Box<T>, Self> {
343        let Self {
344            inner,
345            contexts,
346            severity_override,
347            session_sources,
348            attached_sources,
349        } = self;
350        if inner.as_any().is::<T>() {
351            Ok(inner
352                .into_any()
353                .downcast()
354                .expect("type was checked before consuming owned diagnostic"))
355        } else if inner.as_any().is::<DiagnosticError<T>>() {
356            let diagnostic_error = inner
357                .into_any()
358                .downcast::<DiagnosticError<T>>()
359                .expect("type was checked before consuming owned diagnostic");
360            Ok(Box::new(diagnostic_error.0))
361        } else {
362            Err(Self {
363                inner,
364                contexts,
365                severity_override,
366                session_sources,
367                attached_sources,
368            })
369        }
370    }
371
372    fn prepared<'a>(
373        &'a self,
374        snapshot: crate::DiagnosticSnapshot,
375        session_sources: &'a dyn SourceProvider,
376    ) -> PreparedDiagnostic<'a> {
377        let attached = self.attached_sources().map(|sources| sources as &dyn SourceProvider);
378        PreparedDiagnostic {
379            snapshot,
380            sources: LayeredSourceProvider::new(session_sources, attached),
381        }
382    }
383}
384
385impl fmt::Display for OwnedDiagnostic {
386    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
387        DiagnosticMessage(self.as_diagnostic()).fmt(formatter)
388    }
389}
390
391/// Delegates the semantic diagnostic protocol to the owned occurrence.
392///
393/// Occurrence transport metadata such as context frames and attached source providers is consumed
394/// by [`OwnedDiagnostic::prepare`]; it is intentionally not exposed when an owned diagnostic is
395/// nested as a plain [`Diagnostic`].
396impl Diagnostic for OwnedDiagnostic {
397    fn message(&self, out: &mut dyn fmt::Write) -> fmt::Result {
398        self.as_diagnostic().message(out)
399    }
400
401    fn descriptor(&self) -> Option<&'static DiagnosticDescriptor> {
402        self.as_diagnostic().descriptor()
403    }
404
405    fn code(&self) -> Option<DiagnosticCodeRef<'_>> {
406        self.as_diagnostic().code()
407    }
408
409    fn severity(&self) -> Severity {
410        OwnedDiagnostic::severity(self)
411    }
412
413    fn tags(&self) -> &[DiagnosticTag] {
414        self.as_diagnostic().tags()
415    }
416
417    fn visit(&self, visitor: &mut dyn crate::VisitDiagnostic) {
418        self.as_diagnostic().visit(visitor)
419    }
420
421    fn cause(&self) -> Option<&(dyn core::error::Error + 'static)> {
422        self.as_diagnostic().cause()
423    }
424
425    fn diagnostic_source(&self) -> Option<&dyn Diagnostic> {
426        self.as_diagnostic().diagnostic_source()
427    }
428}
429
430impl fmt::Debug for OwnedDiagnostic {
431    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
432        formatter
433            .debug_struct("OwnedDiagnostic")
434            .field("diagnostic", &self.as_diagnostic())
435            .field("effective_severity", &self.severity())
436            .field("severity_override", &self.severity_override)
437            .field("contexts", &self.contexts)
438            .field("has_session_sources", &self.session_sources.is_some())
439            .field("has_attached_sources", &self.attached_sources.is_some())
440            .finish()
441    }
442}
443
444/// A borrowing adapter for rich formatting of one owned diagnostic.
445///
446/// The adapter uses deterministic [`RenderConfig::DEFAULT`] settings unless
447/// configured otherwise. Its [`fmt::Display`] implementation degrades
448/// preparation and rendering failures to safe text; use [`Self::try_render`]
449/// when those failures must remain observable.
450#[derive(Clone, Copy)]
451#[must_use = "a diagnostic display adapter must be formatted or rendered"]
452pub struct DiagnosticDisplay<'a> {
453    diagnostic: &'a OwnedDiagnostic,
454    session_sources: &'a dyn SourceProvider,
455    config: RenderConfig,
456}
457
458impl<'a> DiagnosticDisplay<'a> {
459    const fn new(diagnostic: &'a OwnedDiagnostic, session_sources: &'a dyn SourceProvider) -> Self {
460        Self {
461            diagnostic,
462            session_sources,
463            config: RenderConfig::DEFAULT,
464        }
465    }
466
467    /// Replaces the renderer configuration used by this adapter.
468    pub const fn with_config(mut self, config: RenderConfig) -> Self {
469        self.config = config;
470        self
471    }
472
473    /// Returns the renderer configuration used by this adapter.
474    pub const fn config(&self) -> RenderConfig {
475        self.config
476    }
477
478    /// Strictly prepares and renders this diagnostic.
479    pub fn try_render(&self) -> Result<String, DiagnosticRenderError> {
480        let diagnostic = self
481            .diagnostic
482            .prepare(self.session_sources)
483            .map_err(DiagnosticRenderError::Prepare)?;
484        AnnotateRenderer::new(self.config)
485            .render(&diagnostic)
486            .map_err(DiagnosticRenderError::Render)
487    }
488
489    fn render_or_degrade(&self) -> String {
490        let Ok(diagnostic) = self.diagnostic.prepare(self.session_sources) else {
491            return String::from(REPORT_PREPARATION_FALLBACK);
492        };
493        render_or_degrade(&AnnotateRenderer::new(self.config), &diagnostic).0
494    }
495}
496
497impl fmt::Display for DiagnosticDisplay<'_> {
498    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
499        formatter.write_str(&self.render_or_degrade())
500    }
501}
502
503/// A failed-computation wrapper that promotes its occurrence to error.
504pub struct Report {
505    inner: Box<OwnedDiagnostic>,
506}
507
508impl Report {
509    /// Creates a failed-computation report from an ad-hoc display message.
510    ///
511    /// The message is formatted immediately, so it may borrow local values and does not need to
512    /// satisfy the owned diagnostic transport bounds.
513    pub fn msg(message: impl fmt::Display) -> Self {
514        Self::new(crate::AdHocDiagnostic::new(format_args!("{message}")))
515    }
516
517    /// Creates a failed-computation report.
518    ///
519    /// ```compile_fail
520    /// extern crate alloc;
521    /// use core::fmt;
522    /// use runic_diagnostics::{Diagnostic, Report};
523    ///
524    /// #[derive(Debug)]
525    /// struct Borrowed<'a>(&'a str);
526    /// impl Diagnostic for Borrowed<'_> {
527    ///     fn message(&self, out: &mut dyn fmt::Write) -> fmt::Result {
528    ///         out.write_str(self.0)
529    ///     }
530    /// }
531    ///
532    /// let text = alloc::string::String::from("local");
533    /// let _ = Report::new(Borrowed(&text));
534    /// ```
535    ///
536    /// ```compile_fail
537    /// extern crate alloc;
538    /// use alloc::rc::Rc;
539    /// use core::{cell::Cell, fmt};
540    /// use runic_diagnostics::{Diagnostic, Report};
541    ///
542    /// #[derive(Debug)]
543    /// struct Local(Rc<Cell<u32>>);
544    /// impl Diagnostic for Local {
545    ///     fn message(&self, out: &mut dyn fmt::Write) -> fmt::Result {
546    ///         write!(out, "{}", self.0.get())
547    ///     }
548    /// }
549    ///
550    /// let _ = Report::new(Local(Rc::new(Cell::new(1))));
551    /// ```
552    pub fn new<T>(diagnostic: T) -> Self
553    where
554        T: Diagnostic + Send + Sync + 'static,
555    {
556        Self {
557            inner: Box::new(
558                OwnedDiagnostic::new(diagnostic).with_severity_override(Severity::Error),
559            ),
560        }
561    }
562
563    pub fn from_diagnostic(mut diagnostic: OwnedDiagnostic) -> Self {
564        diagnostic.set_severity_override(Some(Severity::Error));
565        Self {
566            inner: Box::new(diagnostic),
567        }
568    }
569
570    pub fn from_error<E: core::error::Error + Send + Sync + 'static>(error: E) -> Self {
571        Self::new(DiagnosticError(error))
572    }
573
574    pub fn as_diagnostic(&self) -> &dyn Diagnostic {
575        self.inner.as_diagnostic()
576    }
577
578    pub fn severity(&self) -> Severity {
579        self.inner.severity()
580    }
581
582    pub fn descriptor(&self) -> Option<&'static DiagnosticDescriptor> {
583        self.inner.descriptor()
584    }
585
586    pub fn contexts(&self) -> &[ContextFrame] {
587        self.inner.contexts()
588    }
589
590    pub fn context(mut self, context: impl Into<String>) -> Self {
591        self.inner.push_context(context);
592        self
593    }
594
595    pub fn with_context<F, S>(self, context: F) -> Self
596    where
597        F: FnOnce() -> S,
598        S: Into<String>,
599    {
600        self.context(context())
601    }
602
603    pub fn attach_sources<P>(mut self, sources: P) -> Self
604    where
605        P: SourceProvider + Send + Sync + 'static,
606    {
607        self.inner.attached_sources = Some(Box::new(sources));
608        self
609    }
610
611    /// Retains a session source provider with this report.
612    pub fn attach_session_sources<P>(mut self, sources: P) -> Self
613    where
614        P: SourceProvider + Send + Sync + 'static,
615    {
616        self.inner.set_session_sources(sources);
617        self
618    }
619
620    pub fn session_sources(&self) -> Option<&(dyn SourceProvider + Send + Sync + 'static)> {
621        self.inner.session_sources()
622    }
623
624    pub fn attached_sources(&self) -> Option<&(dyn SourceProvider + Send + Sync + 'static)> {
625        self.inner.attached_sources()
626    }
627
628    /// Prepares this report with its occurrence metadata and source universes.
629    pub fn prepare<'a>(
630        &'a self,
631        session_sources: &'a dyn SourceProvider,
632    ) -> Result<PreparedDiagnostic<'a>, PrepareError> {
633        self.inner.prepare(session_sources)
634    }
635
636    /// Prepares this report with explicit resource limits.
637    pub fn prepare_with_limits<'a>(
638        &'a self,
639        session_sources: &'a dyn SourceProvider,
640        limits: PreparationLimits,
641    ) -> Result<PreparedDiagnostic<'a>, PrepareError> {
642        self.inner.prepare_with_limits(session_sources, limits)
643    }
644
645    /// Prepares this report using only sources attached to it.
646    pub fn prepare_attached(&self) -> Result<PreparedDiagnostic<'_>, PrepareError> {
647        self.inner.prepare_attached()
648    }
649
650    /// Prepares this report using only attached sources and explicit limits.
651    pub fn prepare_attached_with_limits(
652        &self,
653        limits: PreparationLimits,
654    ) -> Result<PreparedDiagnostic<'_>, PrepareError> {
655        self.inner.prepare_attached_with_limits(limits)
656    }
657
658    /// Returns a rich-formatting adapter using attached sources and portable defaults.
659    pub fn display(&self) -> DiagnosticDisplay<'_> {
660        self.inner.display()
661    }
662
663    /// Returns a rich-formatting adapter with an explicit session source provider.
664    pub fn display_with_sources<'a>(
665        &'a self,
666        session_sources: &'a dyn SourceProvider,
667    ) -> DiagnosticDisplay<'a> {
668        self.inner.display_with_sources(session_sources)
669    }
670
671    pub fn is<T: 'static>(&self) -> bool {
672        self.inner.is::<T>()
673    }
674
675    pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
676        self.inner.downcast_ref()
677    }
678
679    pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
680        self.inner.downcast_mut()
681    }
682
683    pub fn downcast<T: 'static>(self) -> Result<Box<T>, Self> {
684        match (*self.inner).downcast() {
685            Ok(value) => Ok(value),
686            Err(inner) => Err(Self {
687                inner: Box::new(inner),
688            }),
689        }
690    }
691
692    pub fn into_diagnostic(self) -> OwnedDiagnostic {
693        *self.inner
694    }
695}
696
697impl fmt::Display for Report {
698    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
699        DiagnosticMessage(self.inner.as_diagnostic()).fmt(formatter)?;
700        if formatter.alternate() {
701            for context in self.inner.contexts().iter().rev() {
702                write!(formatter, "\n  context: {}", context.message())?;
703            }
704            let mut cause = self.inner.as_diagnostic().cause();
705            let mut depth = 0_u8;
706            while let Some(error) = cause {
707                write!(formatter, "\n  caused by: {error}")?;
708                cause = error.source();
709                depth = depth.saturating_add(1);
710                if depth == 64 && cause.is_some() {
711                    formatter.write_str("\n  caused by: <cause depth limit reached>")?;
712                    break;
713                }
714            }
715        }
716        Ok(())
717    }
718}
719
720impl fmt::Debug for Report {
721    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
722        fmt::Display::fmt(&self.display(), formatter)
723    }
724}
725
726impl core::error::Error for Report {
727    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
728        self.inner.as_diagnostic().cause()
729    }
730}
731
732impl From<Report> for OwnedDiagnostic {
733    fn from(report: Report) -> Self {
734        report.into_diagnostic()
735    }
736}
737
738impl<T: Diagnostic + Send + Sync + 'static> From<T> for Report {
739    fn from(value: T) -> Self {
740        Report::new(value)
741    }
742}
743
744/// Convenience [`Diagnostic`] that can be used as an "anonymous" wrapper for
745/// Errors. This is intended to be paired with [`IntoDiagnostic`].
746#[derive(Debug)]
747#[repr(transparent)]
748struct DiagnosticError<T>(T);
749
750impl<T> AsRef<T> for DiagnosticError<T> {
751    #[inline(always)]
752    fn as_ref(&self) -> &T {
753        &self.0
754    }
755}
756
757impl<T> AsMut<T> for DiagnosticError<T> {
758    #[inline(always)]
759    fn as_mut(&mut self) -> &mut T {
760        &mut self.0
761    }
762}
763
764impl<T: fmt::Display> fmt::Display for DiagnosticError<T> {
765    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
766        fmt::Display::fmt(&self.0, f)
767    }
768}
769
770impl<T: core::error::Error> core::error::Error for DiagnosticError<T> {
771    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
772        self.0.source()
773    }
774}
775
776impl<T: core::error::Error + 'static> Diagnostic for DiagnosticError<T> {
777    fn message(&self, out: &mut dyn fmt::Write) -> fmt::Result {
778        out.write_fmt(format_args!("{}", self.0))
779    }
780
781    fn cause(&self) -> Option<&(dyn core::error::Error + 'static)> {
782        self.0.source()
783    }
784}
785
786/// Converts a set of independent diagnostics into a single diagnostic convertible to [Report]
787#[derive(Debug)]
788pub(crate) struct DiagnosticBundle {
789    primary: OwnedDiagnostic,
790    related: Vec<OwnedDiagnostic>,
791}
792
793impl DiagnosticBundle {
794    pub fn new(primary: OwnedDiagnostic, related: Vec<OwnedDiagnostic>) -> Self {
795        Self { primary, related }
796    }
797
798    /// Converts this bundle into a [Report] that retains the primary's session sources.
799    ///
800    /// The bundled diagnostics are rendered with the outer report's session sources, so those of
801    /// the primary are moved onto it.
802    pub fn into_report(mut self) -> Report {
803        let session_sources = self.primary.session_sources.take();
804        let mut report = Report::new(self);
805        report.inner.session_sources = session_sources;
806        report
807    }
808}
809
810impl Diagnostic for DiagnosticBundle {
811    fn message(&self, out: &mut dyn core::fmt::Write) -> core::fmt::Result {
812        self.primary.message(out)
813    }
814
815    fn descriptor(&self) -> Option<&'static DiagnosticDescriptor> {
816        self.primary.descriptor()
817    }
818
819    fn code(&self) -> Option<DiagnosticCodeRef<'_>> {
820        self.primary.code()
821    }
822
823    fn severity(&self) -> Severity {
824        self.primary.severity()
825    }
826
827    fn tags(&self) -> &[DiagnosticTag] {
828        self.primary.tags()
829    }
830
831    fn visit(&self, visitor: &mut dyn crate::VisitDiagnostic) {
832        self.primary.visit(visitor);
833        for diagnostic in &self.related {
834            visitor.related(diagnostic);
835        }
836    }
837
838    fn cause(&self) -> Option<&(dyn core::error::Error + 'static)> {
839        self.primary.cause()
840    }
841
842    fn diagnostic_source(&self) -> Option<&dyn Diagnostic> {
843        self.primary.diagnostic_source()
844    }
845}
846
847#[cfg(test)]
848mod tests {
849    use alloc::{boxed::Box, format, string::ToString};
850    use core::fmt::Write;
851
852    use super::*;
853    use crate::{
854        DescriptorOrigin, DiagnosticCode, DiagnosticDescriptor, DiagnosticTag, Explanation, Label,
855        LabelStyle, SourceMap, SourceNamespace, SourceRevision, SourceSpan, TextRange,
856        VisitDiagnostic,
857    };
858
859    static WARNING: DiagnosticDescriptor = DiagnosticDescriptor {
860        code: DiagnosticCode {
861            namespace: "test",
862            code: "W0001",
863        },
864        summary: "warning",
865        default_severity: Severity::Warning,
866        explanation: Explanation::NotProvided,
867        documentation_url: None,
868        tags: &[DiagnosticTag::Deprecated],
869        origin: DescriptorOrigin {
870            module_path: module_path!(),
871            file: file!(),
872            line: line!(),
873        },
874    };
875
876    #[derive(Debug)]
877    struct Mutable(u32);
878
879    impl Diagnostic for Mutable {
880        fn message(&self, out: &mut dyn Write) -> fmt::Result {
881            write!(out, "value {}", self.0)
882        }
883    }
884
885    #[test]
886    fn hidden_erasure_supports_all_safe_downcast_paths() {
887        fn require_transport<T: Send + Sync + 'static>() {}
888        require_transport::<OwnedDiagnostic>();
889        require_transport::<Report>();
890
891        let mut owned = OwnedDiagnostic::new(Mutable(1));
892        assert!(owned.is::<Mutable>());
893        assert_eq!(owned.downcast_ref::<Mutable>().unwrap().0, 1);
894        owned.downcast_mut::<Mutable>().unwrap().0 = 2;
895        assert_eq!(owned.downcast::<Mutable>().unwrap().0, 2);
896
897        let mut sources = SourceMap::new(SourceNamespace::new_unchecked(9));
898        let source_id = sources.insert("attached", "text", None).unwrap();
899        let failed = OwnedDiagnostic::new(Mutable(3))
900            .with_context("kept")
901            .attach_sources(sources)
902            .downcast::<alloc::string::String>()
903            .unwrap_err();
904        assert_eq!(failed.contexts()[0].message(), "kept");
905        assert_eq!(failed.attached_sources().unwrap().get(source_id).unwrap().text, Some("text"));
906
907        let report = Report::new(Mutable(4))
908            .context("report context")
909            .downcast::<alloc::string::String>()
910            .unwrap_err();
911        assert_eq!(report.severity(), Severity::Error);
912        assert_eq!(report.contexts()[0].message(), "report context");
913        assert_eq!(report.downcast_ref::<Mutable>().unwrap().0, 4);
914    }
915
916    #[test]
917    fn report_is_a_pointer_sized_failure_handle() {
918        assert_eq!(core::mem::size_of::<Report>(), core::mem::size_of::<usize>());
919    }
920
921    #[derive(Debug)]
922    struct Warning;
923
924    impl Diagnostic for Warning {
925        fn message(&self, out: &mut dyn Write) -> fmt::Result {
926            out.write_str("warning occurrence")
927        }
928
929        fn descriptor(&self) -> Option<&'static DiagnosticDescriptor> {
930            Some(&WARNING)
931        }
932    }
933
934    #[test]
935    fn report_promotes_occurrence_without_mutating_descriptor_identity() {
936        let owned = OwnedDiagnostic::new(Warning);
937        assert_eq!(owned.severity(), Severity::Warning);
938        assert!(core::ptr::eq(owned.descriptor().unwrap(), &WARNING));
939
940        let report = Report::new(Warning).context("inner").with_context(|| "outer".to_string());
941        assert_eq!(report.severity(), Severity::Error);
942        assert!(core::ptr::eq(report.descriptor().unwrap(), &WARNING));
943        assert_eq!(WARNING.default_severity, Severity::Warning);
944        assert_eq!(report.to_string(), "warning occurrence");
945        assert_eq!(format!("{report:#}"), "warning occurrence\n  context: outer\n  context: inner");
946
947        let diagnostic = report.into_diagnostic();
948        assert_eq!(diagnostic.severity(), Severity::Error);
949        assert!(core::ptr::eq(diagnostic.descriptor().unwrap(), &WARNING));
950    }
951
952    #[test]
953    fn report_msg_formats_borrowed_values_immediately() {
954        let message = String::from("ad-hoc failure");
955        let report = Report::msg(&message);
956        drop(message);
957        assert_eq!(report.to_string(), "ad-hoc failure");
958    }
959
960    #[derive(Debug)]
961    struct LabeledFailure(SourceSpan);
962
963    impl Diagnostic for LabeledFailure {
964        fn message(&self, out: &mut dyn Write) -> fmt::Result {
965            out.write_str("labeled failure")
966        }
967
968        fn visit(&self, visitor: &mut dyn VisitDiagnostic) {
969            visitor.label(Label {
970                span: self.0,
971                style: LabelStyle::Primary,
972                message: Some(format_args!("failure occurred here")),
973            });
974        }
975    }
976
977    #[test]
978    fn report_display_uses_retained_session_sources() {
979        let mut sources = SourceMap::new(SourceNamespace::new_unchecked(12));
980        let id = sources.insert("input.runic", "begin broken end", None).unwrap();
981        let span = SourceSpan::session(id, TextRange::new(6, 12).unwrap());
982        let report = Report::new(LabeledFailure(span)).attach_session_sources(sources);
983
984        let rendered = format!("{report:?}");
985        assert!(rendered.contains("input.runic"));
986        assert!(rendered.contains("broken"));
987        assert!(rendered.contains("failure occurred here"));
988    }
989
990    #[test]
991    fn unknown_labels_do_not_require_a_source_provider() {
992        let report = Report::new(LabeledFailure(SourceSpan::UNKNOWN));
993        let rendered = format!("{report:?}");
994        assert!(rendered.contains("labeled failure"));
995        assert!(!rendered.contains("missing source"));
996    }
997
998    #[derive(Debug)]
999    struct Cause;
1000
1001    impl fmt::Display for Cause {
1002        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1003            formatter.write_str("root cause")
1004        }
1005    }
1006
1007    impl core::error::Error for Cause {}
1008
1009    #[derive(Debug)]
1010    struct WithCause(Cause);
1011
1012    impl Diagnostic for WithCause {
1013        fn message(&self, out: &mut dyn Write) -> fmt::Result {
1014            out.write_str("operation failed")
1015        }
1016
1017        fn cause(&self) -> Option<&(dyn core::error::Error + 'static)> {
1018            Some(&self.0)
1019        }
1020    }
1021
1022    #[test]
1023    fn report_delegates_error_source_and_retains_attached_bundle() {
1024        let mut sources = SourceMap::new(SourceNamespace::new_unchecked(4));
1025        let id = sources.insert("input", "source", Some(SourceRevision(1))).unwrap();
1026        let report = Report::new(WithCause(Cause)).attach_sources(sources);
1027        assert_eq!(core::error::Error::source(&report).unwrap().to_string(), "root cause");
1028        assert_eq!(format!("{report:#}"), "operation failed\n  caused by: root cause");
1029        let diagnostic = report.into_diagnostic();
1030        let source = diagnostic.attached_sources().unwrap().get(id).unwrap();
1031        assert_eq!(source.text, Some("source"));
1032        assert_eq!(source.revision, Some(SourceRevision(1)));
1033    }
1034
1035    #[derive(Debug)]
1036    struct ChainCause(Option<Box<ChainCause>>);
1037
1038    impl fmt::Display for ChainCause {
1039        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1040            formatter.write_str("chain")
1041        }
1042    }
1043
1044    impl core::error::Error for ChainCause {
1045        fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
1046            self.0.as_deref().map(|cause| cause as &(dyn core::error::Error + 'static))
1047        }
1048    }
1049
1050    #[derive(Debug)]
1051    struct WithChain(ChainCause);
1052
1053    impl Diagnostic for WithChain {
1054        fn message(&self, out: &mut dyn Write) -> fmt::Result {
1055            out.write_str("with chain")
1056        }
1057
1058        fn cause(&self) -> Option<&(dyn core::error::Error + 'static)> {
1059            Some(&self.0)
1060        }
1061    }
1062
1063    fn cause_chain(length: usize) -> ChainCause {
1064        let mut cause = None;
1065        for _ in 0..length {
1066            cause = Some(Box::new(ChainCause(cause)));
1067        }
1068        *cause.expect("test cause chain must be nonempty")
1069    }
1070
1071    #[test]
1072    fn alternate_display_marks_only_a_genuinely_truncated_cause_chain() {
1073        let exact_limit = format!("{:#}", Report::new(WithChain(cause_chain(64))));
1074        assert_eq!(exact_limit.matches("\n  caused by: chain").count(), 64);
1075        assert!(!exact_limit.contains("<cause depth limit reached>"));
1076
1077        let over_limit = format!("{:#}", Report::new(WithChain(cause_chain(65))));
1078        assert_eq!(over_limit.matches("\n  caused by: chain").count(), 64);
1079        assert!(over_limit.ends_with("\n  caused by: <cause depth limit reached>"));
1080    }
1081
1082    #[test]
1083    fn equal_attached_source_ids_remain_scoped_to_their_own_occurrence() {
1084        let namespace = SourceNamespace::new_unchecked(12);
1085        let mut first_sources = SourceMap::new(namespace);
1086        let mut second_sources = SourceMap::new(namespace);
1087        let first_id = first_sources.insert("same", "first", None).unwrap();
1088        let second_id = second_sources.insert("same", "second", None).unwrap();
1089        assert_eq!(first_id, second_id);
1090
1091        let first = OwnedDiagnostic::new(Mutable(1)).attach_sources(first_sources);
1092        let second = OwnedDiagnostic::new(Mutable(2)).attach_sources(second_sources);
1093
1094        assert_eq!(first.attached_sources().unwrap().get(first_id).unwrap().text, Some("first"));
1095        assert_eq!(second.attached_sources().unwrap().get(second_id).unwrap().text, Some("second"));
1096    }
1097}