Skip to main content

runic_diagnostics/
snapshot.rs

1use alloc::{boxed::Box, string::String, vec::Vec};
2use core::{error::Error, fmt, slice};
3
4use crate::{
5    Applicability, Diagnostic, DiagnosticCodeRef, DiagnosticDescriptor, DiagnosticInstanceId,
6    DiagnosticMetadata, DiagnosticSet, DiagnosticTag, Label, LabelStyle, LayeredSourceProvider,
7    Note, NoteKind, OwnedDiagnostic, SourceProvider, SourceSpan, Suggestion, TextEdit,
8    VisitDiagnostic, VisitTextEdit, VisitTextEdits, source::EMPTY_SOURCE_PROVIDER,
9};
10
11/// An owned, exact diagnostic code captured for one occurrence.
12#[derive(Clone, Debug, Eq, Hash, PartialEq)]
13pub struct DiagnosticCodeOwned {
14    pub namespace: String,
15    pub code: String,
16}
17
18impl DiagnosticCodeOwned {
19    pub fn new(namespace: impl Into<String>, code: impl Into<String>) -> Self {
20        Self {
21            namespace: namespace.into(),
22            code: code.into(),
23        }
24    }
25
26    pub fn as_ref(&self) -> DiagnosticCodeRef<'_> {
27        DiagnosticCodeRef {
28            namespace: &self.namespace,
29            code: &self.code,
30        }
31    }
32}
33
34impl From<DiagnosticCodeRef<'_>> for DiagnosticCodeOwned {
35    fn from(code: DiagnosticCodeRef<'_>) -> Self {
36        Self::new(code.namespace, code.code)
37    }
38}
39
40#[derive(Clone, Debug, Eq, PartialEq)]
41pub struct OwnedLabel {
42    pub span: SourceSpan,
43    pub style: LabelStyle,
44    pub message: Option<String>,
45}
46
47#[derive(Clone, Debug, Eq, PartialEq)]
48pub struct OwnedNote {
49    pub kind: NoteKind,
50    pub message: String,
51}
52
53#[derive(Clone, Debug, Eq, PartialEq)]
54pub struct OwnedTextEdit {
55    pub span: SourceSpan,
56    pub replacement: String,
57}
58
59#[derive(Clone, Debug, Eq, PartialEq)]
60pub struct OwnedSuggestion {
61    pub message: String,
62    pub applicability: Applicability,
63    pub edits: Vec<OwnedTextEdit>,
64}
65
66impl VisitTextEdits for Vec<OwnedTextEdit> {
67    fn visit_text_edits(&self, visitor: &mut dyn VisitTextEdit) {
68        for edit in self {
69            visitor.text_edit(TextEdit {
70                span: edit.span,
71                replacement: format_args!("{}", edit.replacement),
72            });
73        }
74    }
75}
76
77#[derive(Clone, Debug, Eq, PartialEq)]
78pub struct OwnedCause {
79    pub message: String,
80}
81
82/// A backend-neutral, source-text-free snapshot of one diagnostic.
83#[derive(Clone, Debug, Eq, PartialEq)]
84pub struct DiagnosticSnapshot {
85    /// Present only for roots prepared from a finalized diagnostic set.
86    pub instance_id: Option<DiagnosticInstanceId>,
87    pub code: Option<DiagnosticCodeOwned>,
88    pub descriptor: Option<&'static DiagnosticDescriptor>,
89    pub tags: Vec<DiagnosticTag>,
90    pub severity: crate::Severity,
91    pub message: String,
92    pub labels: Vec<OwnedLabel>,
93    pub notes: Vec<OwnedNote>,
94    pub suggestions: Vec<OwnedSuggestion>,
95    pub causes: Vec<OwnedCause>,
96    pub diagnostic_source: Option<Box<DiagnosticSnapshot>>,
97    pub related: Vec<DiagnosticSnapshot>,
98    /// Propagation contexts ordered from the outermost frame to the innermost.
99    pub contexts: Vec<String>,
100}
101
102/// Finite resource bounds applied independently to each prepared root.
103#[derive(Clone, Copy, Debug, Eq, PartialEq)]
104pub struct PreparationLimits {
105    pub max_related_depth: usize,
106    pub max_diagnostic_source_depth: usize,
107    pub max_cause_depth: usize,
108    pub max_total_items: usize,
109    pub max_item_text_bytes: usize,
110    pub max_total_text_bytes: usize,
111}
112
113impl PreparationLimits {
114    pub const DEFAULT: Self = Self {
115        max_related_depth: 32,
116        max_diagnostic_source_depth: 32,
117        max_cause_depth: 64,
118        max_total_items: 4096,
119        max_item_text_bytes: 64 * 1024,
120        max_total_text_bytes: 1024 * 1024,
121    };
122}
123
124impl Default for PreparationLimits {
125    fn default() -> Self {
126        Self::DEFAULT
127    }
128}
129
130#[derive(Clone, Copy, Debug, Eq, PartialEq)]
131pub enum PreparationItemKind {
132    CodeNamespace,
133    Code,
134    Message,
135    LabelMessage,
136    NoteMessage,
137    SuggestionMessage,
138    Replacement,
139    Cause,
140    Context,
141}
142
143#[derive(Clone, Copy, Debug, Eq, PartialEq)]
144pub enum DiagnosticRelation {
145    Related,
146    DiagnosticSource,
147}
148
149#[derive(Clone, Debug, Eq, PartialEq)]
150pub enum PrepareError {
151    MessageFormatting,
152    VisitorFormatting {
153        item: PreparationItemKind,
154    },
155    CauseFormatting {
156        depth: usize,
157    },
158    MultiplePrimaryLabels {
159        count: usize,
160    },
161    EmptySuggestion {
162        index: usize,
163    },
164    ItemTooLarge {
165        item: PreparationItemKind,
166        bytes: usize,
167        limit: usize,
168    },
169    ItemLimitExceeded {
170        attempted: usize,
171        limit: usize,
172    },
173    TextLimitExceeded {
174        attempted: usize,
175        limit: usize,
176    },
177    DiagnosticCycle {
178        relation: DiagnosticRelation,
179        depth: usize,
180    },
181    RelatedDepthExceeded {
182        depth: usize,
183        limit: usize,
184    },
185    DiagnosticSourceDepthExceeded {
186        depth: usize,
187        limit: usize,
188    },
189    CauseCycle {
190        depth: usize,
191    },
192    CauseDepthExceeded {
193        depth: usize,
194        limit: usize,
195    },
196}
197
198impl fmt::Display for PrepareError {
199    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
200        match self {
201            Self::MessageFormatting => formatter.write_str("diagnostic message formatting failed"),
202            Self::VisitorFormatting { item } => {
203                write!(formatter, "diagnostic {item:?} formatting failed")
204            }
205            Self::CauseFormatting { depth } => {
206                write!(formatter, "diagnostic cause formatting failed at depth {depth}")
207            }
208            Self::MultiplePrimaryLabels { count } => {
209                write!(formatter, "diagnostic supplied {count} primary labels")
210            }
211            Self::EmptySuggestion { index } => {
212                write!(formatter, "diagnostic suggestion {index} contains no edits")
213            }
214            Self::ItemTooLarge { item, bytes, limit } => {
215                write!(formatter, "diagnostic {item:?} uses {bytes} bytes, limit is {limit}")
216            }
217            Self::ItemLimitExceeded { attempted, limit } => {
218                write!(formatter, "diagnostic item count {attempted} exceeds limit {limit}")
219            }
220            Self::TextLimitExceeded { attempted, limit } => {
221                write!(formatter, "diagnostic text uses {attempted} bytes, limit is {limit}")
222            }
223            Self::DiagnosticCycle { relation, depth } => {
224                write!(formatter, "diagnostic {relation:?} cycle detected at depth {depth}")
225            }
226            Self::RelatedDepthExceeded { depth, limit } => {
227                write!(formatter, "related depth {depth} exceeds limit {limit}")
228            }
229            Self::DiagnosticSourceDepthExceeded { depth, limit } => {
230                write!(formatter, "diagnostic-source depth {depth} exceeds limit {limit}")
231            }
232            Self::CauseCycle { depth } => {
233                write!(formatter, "conventional cause cycle detected at depth {depth}")
234            }
235            Self::CauseDepthExceeded { depth, limit } => {
236                write!(formatter, "conventional cause depth {depth} exceeds limit {limit}")
237            }
238        }
239    }
240}
241
242impl Error for PrepareError {}
243
244/// A prepared snapshot paired with the exact source universes it references.
245pub struct PreparedDiagnostic<'a> {
246    pub snapshot: DiagnosticSnapshot,
247    pub sources: LayeredSourceProvider<'a>,
248}
249
250/// A repeatably iterable prepared diagnostic set.
251pub struct PreparedSet<'a> {
252    diagnostics: Box<[PreparedDiagnostic<'a>]>,
253}
254
255impl<'set> PreparedSet<'set> {
256    pub fn len(&self) -> usize {
257        self.diagnostics.len()
258    }
259
260    pub fn is_empty(&self) -> bool {
261        self.diagnostics.is_empty()
262    }
263
264    pub fn iter(&self) -> slice::Iter<'_, PreparedDiagnostic<'set>> {
265        self.diagnostics.iter()
266    }
267}
268
269impl fmt::Display for PreparedSet<'_> {
270    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271        use crate::{AnnotateRenderer, Emitter, FmtEmitter};
272
273        let mut formatter = FmtEmitter::new(f, AnnotateRenderer::default());
274        match formatter.emit_set(self) {
275            Ok(_) => Ok(()),
276            Err(err) => Err(err.error),
277        }
278    }
279}
280
281impl<'set, 'borrow> IntoIterator for &'borrow PreparedSet<'set> {
282    type IntoIter = slice::Iter<'borrow, PreparedDiagnostic<'set>>;
283    type Item = &'borrow PreparedDiagnostic<'set>;
284
285    fn into_iter(self) -> Self::IntoIter {
286        self.iter()
287    }
288}
289
290pub fn prepare_ref(diagnostic: &dyn Diagnostic) -> Result<DiagnosticSnapshot, PrepareError> {
291    prepare_ref_with_limits(diagnostic, PreparationLimits::default())
292}
293
294pub fn prepare_ref_with_limits(
295    diagnostic: &dyn Diagnostic,
296    limits: PreparationLimits,
297) -> Result<DiagnosticSnapshot, PrepareError> {
298    let metadata = live_metadata(diagnostic);
299    prepare_root(diagnostic, metadata, None, &[], limits)
300}
301
302pub(crate) fn prepare_owned_ref(
303    diagnostic: &OwnedDiagnostic,
304) -> Result<DiagnosticSnapshot, PrepareError> {
305    prepare_owned_ref_with_limits(diagnostic, PreparationLimits::default())
306}
307
308pub(crate) fn prepare_owned_ref_with_limits(
309    diagnostic: &OwnedDiagnostic,
310    limits: PreparationLimits,
311) -> Result<DiagnosticSnapshot, PrepareError> {
312    prepare_root(
313        diagnostic.as_diagnostic(),
314        diagnostic.metadata(),
315        None,
316        diagnostic.contexts(),
317        limits,
318    )
319}
320
321impl DiagnosticSet {
322    /// Prepares this set using the session and attached source providers retained by each
323    /// diagnostic occurrence.
324    pub fn prepare_attached(&self) -> Result<PreparedSet<'_>, PrepareError> {
325        self.prepare_attached_with_limits(PreparationLimits::default())
326    }
327
328    /// Prepares this set using retained providers and explicit resource limits.
329    pub fn prepare_attached_with_limits(
330        &self,
331        limits: PreparationLimits,
332    ) -> Result<PreparedSet<'_>, PrepareError> {
333        self.prepare_entries_with_limits(None, limits)
334    }
335
336    pub fn prepare<'a>(
337        &'a self,
338        session_sources: &'a dyn SourceProvider,
339    ) -> Result<PreparedSet<'a>, PrepareError> {
340        self.prepare_with_limits(session_sources, PreparationLimits::default())
341    }
342
343    pub fn prepare_with_limits<'a>(
344        &'a self,
345        session_sources: &'a dyn SourceProvider,
346        limits: PreparationLimits,
347    ) -> Result<PreparedSet<'a>, PrepareError> {
348        self.prepare_entries_with_limits(Some(session_sources), limits)
349    }
350
351    fn prepare_entries_with_limits<'a>(
352        &'a self,
353        session_sources: Option<&'a dyn SourceProvider>,
354        limits: PreparationLimits,
355    ) -> Result<PreparedSet<'a>, PrepareError> {
356        let mut diagnostics = Vec::with_capacity(self.len());
357        for entry in self.iter() {
358            let metadata = entry.metadata();
359            let snapshot = prepare_root(
360                entry.diagnostic.as_diagnostic(),
361                metadata,
362                Some(entry.id),
363                entry.diagnostic.contexts(),
364                limits,
365            )?;
366            let attached = entry
367                .diagnostic
368                .attached_sources()
369                .map(|sources| sources as &dyn SourceProvider);
370            let session = session_sources.unwrap_or_else(|| {
371                entry
372                    .diagnostic
373                    .session_sources()
374                    .map_or(&EMPTY_SOURCE_PROVIDER as &dyn SourceProvider, |sources| sources)
375            });
376            diagnostics.push(PreparedDiagnostic {
377                snapshot,
378                sources: LayeredSourceProvider::new(session, attached),
379            });
380        }
381        Ok(PreparedSet {
382            diagnostics: diagnostics.into_boxed_slice(),
383        })
384    }
385}
386
387fn prepare_root(
388    diagnostic: &dyn Diagnostic,
389    metadata: DiagnosticMetadata<'_>,
390    instance_id: Option<DiagnosticInstanceId>,
391    contexts: &[crate::ContextFrame],
392    limits: PreparationLimits,
393) -> Result<DiagnosticSnapshot, PrepareError> {
394    let mut state = PreparationState {
395        limits,
396        items: 0,
397        text_bytes: 0,
398    };
399    let mut snapshot = state.prepare_diagnostic(
400        diagnostic,
401        SnapshotMetadata {
402            instance_id,
403            descriptor: metadata.descriptor,
404            code: metadata.code,
405            tags: metadata.tags,
406            severity: metadata.severity,
407        },
408        0,
409        0,
410        None,
411        &[],
412    )?;
413    for context in contexts.iter().rev() {
414        state.add_item()?;
415        snapshot
416            .contexts
417            .push(state.capture_exact_text(PreparationItemKind::Context, context.message())?);
418    }
419    Ok(snapshot)
420}
421
422#[derive(Clone, Copy)]
423struct SnapshotMetadata<'a> {
424    instance_id: Option<DiagnosticInstanceId>,
425    descriptor: Option<&'static DiagnosticDescriptor>,
426    code: Option<DiagnosticCodeRef<'a>>,
427    tags: &'a [DiagnosticTag],
428    severity: crate::Severity,
429}
430
431struct PreparationState {
432    limits: PreparationLimits,
433    items: usize,
434    text_bytes: usize,
435}
436
437impl PreparationState {
438    fn prepare_diagnostic(
439        &mut self,
440        diagnostic: &dyn Diagnostic,
441        metadata: SnapshotMetadata<'_>,
442        related_depth: usize,
443        diagnostic_source_depth: usize,
444        incoming: Option<DiagnosticRelation>,
445        active_diagnostics: &[&dyn Diagnostic],
446    ) -> Result<DiagnosticSnapshot, PrepareError> {
447        if related_depth > self.limits.max_related_depth {
448            return Err(PrepareError::RelatedDepthExceeded {
449                depth: related_depth,
450                limit: self.limits.max_related_depth,
451            });
452        }
453        if diagnostic_source_depth > self.limits.max_diagnostic_source_depth {
454            return Err(PrepareError::DiagnosticSourceDepthExceeded {
455                depth: diagnostic_source_depth,
456                limit: self.limits.max_diagnostic_source_depth,
457            });
458        }
459
460        if active_diagnostics.iter().any(|active| core::ptr::eq(*active, diagnostic)) {
461            let relation = incoming.unwrap_or(DiagnosticRelation::Related);
462            let depth = match relation {
463                DiagnosticRelation::Related => related_depth,
464                DiagnosticRelation::DiagnosticSource => diagnostic_source_depth,
465            };
466            return Err(PrepareError::DiagnosticCycle { relation, depth });
467        }
468        // Keep full trait-object references in this invocation-local stack. Comparing full trait
469        // objects includes their vtables, so a diagnostic and an embedded field at the same data
470        // address are not mistaken for a cycle.
471        let mut active_diagnostics = active_diagnostics.to_vec();
472        active_diagnostics.push(diagnostic);
473        self.prepare_active_diagnostic(
474            diagnostic,
475            metadata,
476            related_depth,
477            diagnostic_source_depth,
478            &active_diagnostics,
479        )
480    }
481
482    fn prepare_active_diagnostic(
483        &mut self,
484        diagnostic: &dyn Diagnostic,
485        metadata: SnapshotMetadata<'_>,
486        related_depth: usize,
487        diagnostic_source_depth: usize,
488        active_diagnostics: &[&dyn Diagnostic],
489    ) -> Result<DiagnosticSnapshot, PrepareError> {
490        self.add_item()?;
491        let code = metadata
492            .code
493            .map(|code| {
494                Ok(DiagnosticCodeOwned {
495                    namespace: self
496                        .capture_exact_text(PreparationItemKind::CodeNamespace, code.namespace)?,
497                    code: self.capture_exact_text(PreparationItemKind::Code, code.code)?,
498                })
499            })
500            .transpose()?;
501        let message = self
502            .capture_text(PreparationItemKind::Message, |out| diagnostic.message(out))
503            .map_err(|error| match error {
504                CaptureError::Formatting => PrepareError::MessageFormatting,
505                CaptureError::Preparation(error) => error,
506            })?;
507
508        let mut visitor = SnapshotVisitor {
509            state: self,
510            labels: Vec::new(),
511            notes: Vec::new(),
512            suggestions: Vec::new(),
513            related: Vec::new(),
514            related_depth,
515            diagnostic_source_depth,
516            active_diagnostics,
517            error: None,
518        };
519        diagnostic.visit(&mut visitor);
520        if let Some(error) = visitor.error {
521            return Err(error);
522        }
523        let SnapshotVisitor {
524            state,
525            mut labels,
526            notes,
527            suggestions,
528            related,
529            ..
530        } = visitor;
531
532        let primary_count =
533            labels.iter().filter(|label| label.style == LabelStyle::Primary).count();
534        if primary_count > 1 {
535            return Err(PrepareError::MultiplePrimaryLabels {
536                count: primary_count,
537            });
538        }
539        if primary_count == 0
540            && let Some(first) = labels.first_mut()
541        {
542            first.style = LabelStyle::Primary;
543        }
544
545        let causes = state.prepare_causes(diagnostic.cause())?;
546        let diagnostic_source = diagnostic
547            .diagnostic_source()
548            .map(|source| {
549                let live = live_metadata(source);
550                let next_depth = diagnostic_source_depth.checked_add(1).ok_or(
551                    PrepareError::DiagnosticSourceDepthExceeded {
552                        depth: usize::MAX,
553                        limit: state.limits.max_diagnostic_source_depth,
554                    },
555                )?;
556                state
557                    .prepare_diagnostic(
558                        source,
559                        SnapshotMetadata {
560                            instance_id: None,
561                            descriptor: live.descriptor,
562                            code: live.code,
563                            tags: live.tags,
564                            severity: live.severity,
565                        },
566                        related_depth,
567                        next_depth,
568                        Some(DiagnosticRelation::DiagnosticSource),
569                        active_diagnostics,
570                    )
571                    .map(Box::new)
572            })
573            .transpose()?;
574
575        Ok(DiagnosticSnapshot {
576            instance_id: metadata.instance_id,
577            code,
578            descriptor: metadata.descriptor,
579            tags: metadata.tags.to_vec(),
580            severity: metadata.severity,
581            message,
582            labels,
583            notes,
584            suggestions,
585            causes,
586            diagnostic_source,
587            related,
588            contexts: Vec::new(),
589        })
590    }
591
592    fn prepare_causes(
593        &mut self,
594        first: Option<&(dyn Error + 'static)>,
595    ) -> Result<Vec<OwnedCause>, PrepareError> {
596        let mut causes = Vec::new();
597        let mut active: Vec<*const ()> = Vec::new();
598        let mut current = first;
599        let mut depth = 1usize;
600        while let Some(cause) = current {
601            if depth > self.limits.max_cause_depth {
602                return Err(PrepareError::CauseDepthExceeded {
603                    depth,
604                    limit: self.limits.max_cause_depth,
605                });
606            }
607            let pointer = (cause as *const dyn Error).cast::<()>();
608            if active.iter().any(|candidate| core::ptr::eq(*candidate, pointer)) {
609                return Err(PrepareError::CauseCycle { depth });
610            }
611            active.push(pointer);
612            self.add_item()?;
613            let message = self
614                .capture_text(PreparationItemKind::Cause, |out| write!(out, "{cause}"))
615                .map_err(|error| match error {
616                    CaptureError::Formatting => PrepareError::CauseFormatting { depth },
617                    CaptureError::Preparation(error) => error,
618                })?;
619            causes.push(OwnedCause { message });
620            current = cause.source();
621            if current.is_some() {
622                depth = depth.checked_add(1).ok_or(PrepareError::CauseDepthExceeded {
623                    depth: usize::MAX,
624                    limit: self.limits.max_cause_depth,
625                })?;
626            }
627        }
628        Ok(causes)
629    }
630
631    fn add_item(&mut self) -> Result<(), PrepareError> {
632        let attempted = self.items.checked_add(1).ok_or(PrepareError::ItemLimitExceeded {
633            attempted: usize::MAX,
634            limit: self.limits.max_total_items,
635        })?;
636        if attempted > self.limits.max_total_items {
637            return Err(PrepareError::ItemLimitExceeded {
638                attempted,
639                limit: self.limits.max_total_items,
640            });
641        }
642        self.items = attempted;
643        Ok(())
644    }
645
646    fn capture_text(
647        &mut self,
648        kind: PreparationItemKind,
649        write: impl FnOnce(&mut dyn fmt::Write) -> fmt::Result,
650    ) -> Result<String, CaptureError> {
651        let mut writer = BoundedTextWriter {
652            output: String::new(),
653            kind,
654            item_limit: self.limits.max_item_text_bytes,
655            total_start: self.text_bytes,
656            total_limit: self.limits.max_total_text_bytes,
657            error: None,
658        };
659        if write(&mut writer).is_err() {
660            return Err(writer.error.map_or(CaptureError::Formatting, CaptureError::Preparation));
661        }
662        self.text_bytes = self
663            .text_bytes
664            .checked_add(writer.output.len())
665            .expect("the bounded writer rejected cumulative text overflow");
666        Ok(writer.output)
667    }
668
669    fn capture_exact_text(
670        &mut self,
671        kind: PreparationItemKind,
672        text: &str,
673    ) -> Result<String, PrepareError> {
674        self.capture_text(kind, |out| out.write_str(text)).map_err(|error| match error {
675            CaptureError::Formatting => PrepareError::VisitorFormatting { item: kind },
676            CaptureError::Preparation(error) => error,
677        })
678    }
679}
680
681enum CaptureError {
682    Formatting,
683    Preparation(PrepareError),
684}
685
686impl From<PrepareError> for CaptureError {
687    fn from(error: PrepareError) -> Self {
688        Self::Preparation(error)
689    }
690}
691
692struct BoundedTextWriter {
693    output: String,
694    kind: PreparationItemKind,
695    item_limit: usize,
696    total_start: usize,
697    total_limit: usize,
698    error: Option<PrepareError>,
699}
700
701impl fmt::Write for BoundedTextWriter {
702    fn write_str(&mut self, text: &str) -> fmt::Result {
703        let Some(item_bytes) = self.output.len().checked_add(text.len()) else {
704            self.error = Some(PrepareError::ItemTooLarge {
705                item: self.kind,
706                bytes: usize::MAX,
707                limit: self.item_limit,
708            });
709            return Err(fmt::Error);
710        };
711        if item_bytes > self.item_limit {
712            self.error = Some(PrepareError::ItemTooLarge {
713                item: self.kind,
714                bytes: item_bytes,
715                limit: self.item_limit,
716            });
717            return Err(fmt::Error);
718        }
719        let Some(total_bytes) = self.total_start.checked_add(item_bytes) else {
720            self.error = Some(PrepareError::TextLimitExceeded {
721                attempted: usize::MAX,
722                limit: self.total_limit,
723            });
724            return Err(fmt::Error);
725        };
726        if total_bytes > self.total_limit {
727            self.error = Some(PrepareError::TextLimitExceeded {
728                attempted: total_bytes,
729                limit: self.total_limit,
730            });
731            return Err(fmt::Error);
732        }
733        self.output.push_str(text);
734        Ok(())
735    }
736}
737
738struct SnapshotVisitor<'a, 'diagnostic> {
739    state: &'a mut PreparationState,
740    active_diagnostics: &'diagnostic [&'diagnostic dyn Diagnostic],
741    labels: Vec<OwnedLabel>,
742    notes: Vec<OwnedNote>,
743    suggestions: Vec<OwnedSuggestion>,
744    related: Vec<DiagnosticSnapshot>,
745    related_depth: usize,
746    diagnostic_source_depth: usize,
747    error: Option<PrepareError>,
748}
749
750impl SnapshotVisitor<'_, '_> {
751    fn capture_arguments(
752        &mut self,
753        kind: PreparationItemKind,
754        arguments: fmt::Arguments<'_>,
755    ) -> Result<String, PrepareError> {
756        self.state
757            .capture_text(kind, |out| out.write_fmt(arguments))
758            .map_err(|error| match error {
759                CaptureError::Formatting => PrepareError::VisitorFormatting { item: kind },
760                CaptureError::Preparation(error) => error,
761            })
762    }
763
764    fn fail(&mut self, result: Result<(), PrepareError>) {
765        if let Err(error) = result
766            && self.error.is_none()
767        {
768            self.error = Some(error);
769        }
770    }
771}
772
773impl VisitDiagnostic for SnapshotVisitor<'_, '_> {
774    fn label(&mut self, label: Label<'_>) {
775        if self.error.is_some() {
776            return;
777        }
778        // Unknown and synthetic spans deliberately carry no resolvable source provenance. They
779        // are useful sentinels in diagnostics that may or may not have source context, but must
780        // not turn an otherwise renderable message into a missing-source failure.
781        if label.span.is_unknown() || label.span.is_synthetic() {
782            return;
783        }
784        let result = (|| {
785            self.state.add_item()?;
786            let message = label
787                .message
788                .map(|message| self.capture_arguments(PreparationItemKind::LabelMessage, message))
789                .transpose()?;
790            self.labels.push(OwnedLabel {
791                span: label.span,
792                style: label.style,
793                message,
794            });
795            Ok(())
796        })();
797        self.fail(result);
798    }
799
800    fn note(&mut self, note: Note<'_>) {
801        if self.error.is_some() {
802            return;
803        }
804        let result = (|| {
805            self.state.add_item()?;
806            let message = self.capture_arguments(PreparationItemKind::NoteMessage, note.message)?;
807            self.notes.push(OwnedNote {
808                kind: note.kind,
809                message,
810            });
811            Ok(())
812        })();
813        self.fail(result);
814    }
815
816    fn suggestion(&mut self, suggestion: Suggestion<'_>) {
817        if self.error.is_some() {
818            return;
819        }
820        let index = self.suggestions.len();
821        let result = (|| {
822            self.state.add_item()?;
823            let message =
824                self.capture_arguments(PreparationItemKind::SuggestionMessage, suggestion.message)?;
825            let mut edit_visitor = SnapshotEditVisitor {
826                state: self.state,
827                edits: Vec::new(),
828                error: None,
829            };
830            suggestion.edits.visit_text_edits(&mut edit_visitor);
831            if let Some(error) = edit_visitor.error {
832                return Err(error);
833            }
834            let edits = edit_visitor.edits;
835            if edits.is_empty() {
836                return Err(PrepareError::EmptySuggestion { index });
837            }
838            self.suggestions.push(OwnedSuggestion {
839                message,
840                applicability: suggestion.applicability,
841                edits,
842            });
843            Ok(())
844        })();
845        self.fail(result);
846    }
847
848    fn related(&mut self, diagnostic: &dyn Diagnostic) {
849        if self.error.is_some() {
850            return;
851        }
852        let live = live_metadata(diagnostic);
853        let next_depth = match self.related_depth.checked_add(1) {
854            Some(depth) => depth,
855            None => {
856                self.error = Some(PrepareError::RelatedDepthExceeded {
857                    depth: usize::MAX,
858                    limit: self.state.limits.max_related_depth,
859                });
860                return;
861            }
862        };
863        let result = self
864            .state
865            .prepare_diagnostic(
866                diagnostic,
867                SnapshotMetadata {
868                    instance_id: None,
869                    descriptor: live.descriptor,
870                    code: live.code,
871                    tags: live.tags,
872                    severity: live.severity,
873                },
874                next_depth,
875                self.diagnostic_source_depth,
876                Some(DiagnosticRelation::Related),
877                self.active_diagnostics,
878            )
879            .map(|snapshot| self.related.push(snapshot));
880        self.fail(result);
881    }
882}
883
884struct SnapshotEditVisitor<'a> {
885    state: &'a mut PreparationState,
886    edits: Vec<OwnedTextEdit>,
887    error: Option<PrepareError>,
888}
889
890impl VisitTextEdit for SnapshotEditVisitor<'_> {
891    fn text_edit(&mut self, edit: TextEdit<'_>) {
892        if self.error.is_some() {
893            return;
894        }
895        let result = (|| {
896            self.state.add_item()?;
897            let replacement = self
898                .state
899                .capture_text(PreparationItemKind::Replacement, |out| {
900                    out.write_fmt(edit.replacement)
901                })
902                .map_err(|error| match error {
903                    CaptureError::Formatting => PrepareError::VisitorFormatting {
904                        item: PreparationItemKind::Replacement,
905                    },
906                    CaptureError::Preparation(error) => error,
907                })?;
908            self.edits.push(OwnedTextEdit {
909                span: edit.span,
910                replacement,
911            });
912            Ok(())
913        })();
914        if let Err(error) = result {
915            self.error = Some(error);
916        }
917    }
918}
919
920fn live_metadata(diagnostic: &dyn Diagnostic) -> DiagnosticMetadata<'_> {
921    DiagnosticMetadata {
922        descriptor: diagnostic.descriptor(),
923        code: diagnostic.code(),
924        severity: diagnostic.severity(),
925        tags: diagnostic.tags(),
926    }
927}