Skip to main content

runic_diagnostics/
emit.rs

1use alloc::{format, string::String};
2use core::{error::Error, fmt};
3
4use crate::{
5    AnnotateRenderer, PreparedDiagnostic, PreparedSet, Severity,
6    render::{normalize_display_text, sanitize_rendered_output},
7};
8
9#[derive(Clone, Copy, Debug, Eq, PartialEq)]
10pub enum EmissionStatus {
11    Rendered,
12    Degraded,
13}
14
15#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
16pub struct EmissionSummary {
17    pub emitted: usize,
18    pub degraded: usize,
19}
20
21impl EmissionSummary {
22    fn record(&mut self, status: EmissionStatus) {
23        self.emitted = self.emitted.saturating_add(1);
24        if status == EmissionStatus::Degraded {
25            self.degraded = self.degraded.saturating_add(1);
26        }
27    }
28}
29
30#[derive(Debug)]
31pub struct EmissionFailure<E> {
32    pub error: E,
33    pub completed: EmissionSummary,
34}
35
36impl<E: fmt::Display> fmt::Display for EmissionFailure<E> {
37    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
38        write!(
39            formatter,
40            "diagnostic emission failed after {} records: {}",
41            self.completed.emitted, self.error
42        )
43    }
44}
45
46impl<E> Error for EmissionFailure<E>
47where
48    E: Error + 'static,
49{
50    fn source(&self) -> Option<&(dyn Error + 'static)> {
51        Some(&self.error)
52    }
53}
54
55/// Object-safe presentation boundary. Emission never decides failure policy.
56pub trait Emitter {
57    type Error;
58
59    fn emit(&mut self, diagnostic: &PreparedDiagnostic<'_>) -> Result<EmissionStatus, Self::Error>;
60
61    fn emit_set(
62        &mut self,
63        diagnostics: &PreparedSet<'_>,
64    ) -> Result<EmissionSummary, EmissionFailure<Self::Error>> {
65        let mut completed = EmissionSummary::default();
66        for diagnostic in diagnostics {
67            match self.emit(diagnostic) {
68                Ok(status) => completed.record(status),
69                Err(error) => return Err(EmissionFailure { error, completed }),
70            }
71        }
72        Ok(completed)
73    }
74}
75
76pub struct FmtEmitter<W: fmt::Write> {
77    writer: W,
78    renderer: AnnotateRenderer,
79}
80
81impl<W: fmt::Write> FmtEmitter<W> {
82    pub const fn new(writer: W, renderer: AnnotateRenderer) -> Self {
83        Self { writer, renderer }
84    }
85
86    pub const fn renderer(&self) -> &AnnotateRenderer {
87        &self.renderer
88    }
89
90    pub fn renderer_mut(&mut self) -> &mut AnnotateRenderer {
91        &mut self.renderer
92    }
93
94    pub const fn writer(&self) -> &W {
95        &self.writer
96    }
97
98    pub fn writer_mut(&mut self) -> &mut W {
99        &mut self.writer
100    }
101
102    pub fn into_inner(self) -> W {
103        self.writer
104    }
105
106    fn record(&self, diagnostic: &PreparedDiagnostic<'_>) -> (String, EmissionStatus) {
107        render_or_degrade(&self.renderer, diagnostic)
108    }
109}
110
111impl<W: fmt::Write> Emitter for FmtEmitter<W> {
112    type Error = fmt::Error;
113
114    fn emit(&mut self, diagnostic: &PreparedDiagnostic<'_>) -> Result<EmissionStatus, Self::Error> {
115        let (record, status) = self.record(diagnostic);
116        self.writer.write_str(&record)?;
117        self.writer.write_char('\n')?;
118        Ok(status)
119    }
120}
121
122#[cfg(feature = "std")]
123#[derive(Debug)]
124pub enum IoEmissionError {
125    Write(std::io::Error),
126    Flush(std::io::Error),
127}
128
129#[cfg(feature = "std")]
130impl fmt::Display for IoEmissionError {
131    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
132        match self {
133            Self::Write(error) => write!(formatter, "diagnostic write failed: {error}"),
134            Self::Flush(error) => write!(formatter, "diagnostic flush failed: {error}"),
135        }
136    }
137}
138
139#[cfg(feature = "std")]
140impl Error for IoEmissionError {
141    fn source(&self) -> Option<&(dyn Error + 'static)> {
142        match self {
143            Self::Write(error) | Self::Flush(error) => Some(error),
144        }
145    }
146}
147
148#[cfg(feature = "std")]
149pub struct IoEmitter<W: std::io::Write> {
150    writer: W,
151    renderer: AnnotateRenderer,
152}
153
154#[cfg(feature = "std")]
155impl<W: std::io::Write> IoEmitter<W> {
156    pub const fn new(writer: W, renderer: AnnotateRenderer) -> Self {
157        Self { writer, renderer }
158    }
159
160    pub const fn renderer(&self) -> &AnnotateRenderer {
161        &self.renderer
162    }
163
164    pub fn renderer_mut(&mut self) -> &mut AnnotateRenderer {
165        &mut self.renderer
166    }
167
168    pub const fn writer(&self) -> &W {
169        &self.writer
170    }
171
172    pub fn writer_mut(&mut self) -> &mut W {
173        &mut self.writer
174    }
175
176    pub fn into_inner(self) -> W {
177        self.writer
178    }
179
180    fn write_record(
181        &mut self,
182        diagnostic: &PreparedDiagnostic<'_>,
183    ) -> Result<EmissionStatus, IoEmissionError> {
184        let (record, status) = render_or_degrade(&self.renderer, diagnostic);
185        self.writer.write_all(record.as_bytes()).map_err(IoEmissionError::Write)?;
186        self.writer.write_all(b"\n").map_err(IoEmissionError::Write)?;
187        Ok(status)
188    }
189}
190
191#[cfg(feature = "std")]
192impl<W: std::io::Write> Emitter for IoEmitter<W> {
193    type Error = IoEmissionError;
194
195    fn emit(&mut self, diagnostic: &PreparedDiagnostic<'_>) -> Result<EmissionStatus, Self::Error> {
196        let status = self.write_record(diagnostic)?;
197        self.writer.flush().map_err(IoEmissionError::Flush)?;
198        Ok(status)
199    }
200
201    fn emit_set(
202        &mut self,
203        diagnostics: &PreparedSet<'_>,
204    ) -> Result<EmissionSummary, EmissionFailure<Self::Error>> {
205        let mut completed = EmissionSummary::default();
206        for diagnostic in diagnostics {
207            match self.write_record(diagnostic) {
208                Ok(status) => completed.record(status),
209                Err(error) => return Err(EmissionFailure { error, completed }),
210            }
211        }
212        if let Err(error) = self.writer.flush() {
213            return Err(EmissionFailure {
214                error: IoEmissionError::Flush(error),
215                completed,
216            });
217        }
218        Ok(completed)
219    }
220}
221
222pub(crate) fn render_or_degrade(
223    renderer: &AnnotateRenderer,
224    diagnostic: &PreparedDiagnostic<'_>,
225) -> (String, EmissionStatus) {
226    match renderer.render(diagnostic) {
227        Ok(output) => (output, EmissionStatus::Rendered),
228        Err(error) => (degraded_fallback(diagnostic, error.category()), EmissionStatus::Degraded),
229    }
230}
231
232fn degraded_fallback(diagnostic: &PreparedDiagnostic<'_>, category: &'static str) -> String {
233    let snapshot = &diagnostic.snapshot;
234    let severity = severity_name(snapshot.severity);
235    let code = snapshot
236        .code
237        .as_ref()
238        .map(|code| normalize_display_text(&format!("{}/{}", code.namespace, code.code)));
239    let message = normalize_display_text(&snapshot.message);
240    let title = match code {
241        Some(code) => format!("{severity}[{code}]: {message}"),
242        None => format!("{severity}: {message}"),
243    };
244    let fallback = format!("{title}\nnote: diagnostic rendering degraded: {category}");
245    sanitize_rendered_output(&fallback, false, false, &[])
246}
247
248fn severity_name(severity: Severity) -> &'static str {
249    match severity {
250        Severity::Error => "error",
251        Severity::Warning => "warning",
252        Severity::Info => "info",
253        Severity::Hint => "hint",
254    }
255}