Skip to main content

fic/
error.rs

1//! Compiler diagnostic types for the Fiducia language.
2//!
3//! Provides [`Diagnostic`] (a single error or warning with source context)
4//! and [`Diagnostics`] (a collection that implements [`Error`] for use with
5//! `anyhow`). Renders rustc-style diagnostics via
6//! [`annotate-snippets`](https://docs.rs/annotate-snippets).
7//!
8//! A pass collects both severities into one `Vec<Diagnostic>` as it walks;
9//! at the end it drains the warnings with [`Diagnostics::warnings`] for the
10//! caller to print, then decides `Ok`/`Err` on the errors with
11//! [`Diagnostics::finish`].
12
13use std::error::Error;
14use std::fmt::{self, Display, Formatter};
15use std::fs;
16use std::ops::Range;
17use std::path::Path;
18
19use annotate_snippets::{AnnotationKind, Level, Renderer, Snippet};
20use winnow::error::{ContextError, ParseError};
21
22/// Whether a diagnostic fails its pass.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum Severity {
25    /// Fails the pass.
26    Error,
27    /// Printed; the pass goes on.
28    Warning,
29}
30
31impl Severity {
32    fn label(self) -> &'static str {
33        match self {
34            Severity::Error => "error",
35            Severity::Warning => "warning",
36        }
37    }
38
39    fn level(self) -> Level<'static> {
40        match self {
41            Severity::Error => Level::ERROR,
42            Severity::Warning => Level::WARNING,
43        }
44    }
45}
46
47/// A compiler diagnostic with source context for rich rendering.
48///
49/// Displays as a rustc-style diagnostic with the span highlighted in the
50/// original source text.
51#[derive(Debug, Clone)]
52pub struct Diagnostic {
53    severity: Severity,
54    message: String,
55    span: Range<usize>,
56    input: Option<String>,
57    filename: Option<String>,
58}
59
60impl Diagnostic {
61    /// Create an error with source text for rich snippet rendering.
62    pub fn new(message: String, span: Range<usize>, input: String) -> Self {
63        Self {
64            severity: Severity::Error,
65            message,
66            span,
67            input: Some(input),
68            filename: None,
69        }
70    }
71
72    /// Create an error without source text (for a pass that has only the span).
73    ///
74    /// Call [`resolve_source`](Self::resolve_source) later to load source
75    /// from the file for rich rendering.
76    pub fn at(message: String, span: Range<usize>, filename: impl AsRef<Path>) -> Self {
77        Self {
78            severity: Severity::Error,
79            message,
80            span,
81            input: None,
82            filename: Some(filename.as_ref().display().to_string()),
83        }
84    }
85
86    /// Create a warning without source text.
87    pub fn warn_at(message: String, span: Range<usize>, filename: impl AsRef<Path>) -> Self {
88        Self {
89            severity: Severity::Warning,
90            ..Self::at(message, span, filename)
91        }
92    }
93
94    /// The same finding, as a warning: printed, and the pass goes on.
95    #[must_use]
96    pub fn as_warning(self) -> Self {
97        Self {
98            severity: Severity::Warning,
99            ..self
100        }
101    }
102
103    /// Convert a winnow `ParseError` into an error.
104    pub fn from_parse(error: &ParseError<&str, ContextError>) -> Self {
105        let message = error.inner().to_string();
106        let input = (*error.input()).to_owned();
107        let span = error.char_span();
108        Self {
109            severity: Severity::Error,
110            message,
111            span,
112            input: Some(input),
113            filename: None,
114        }
115    }
116
117    /// Error or warning.
118    pub fn severity(&self) -> Severity {
119        self.severity
120    }
121
122    /// Attach a filename for display in the snippet origin.
123    pub fn with_filename(mut self, filename: impl Into<String>) -> Self {
124        self.filename = Some(filename.into());
125        self
126    }
127
128    /// Returns the diagnostic message.
129    pub fn message(&self) -> &str {
130        &self.message
131    }
132
133    /// Returns the byte span of the error in the source.
134    pub fn span(&self) -> &Range<usize> {
135        &self.span
136    }
137
138    /// Returns the source text, if available.
139    pub fn input(&self) -> Option<&str> {
140        self.input.as_deref()
141    }
142
143    /// Returns the source filename, if set.
144    pub fn filename(&self) -> Option<&str> {
145        self.filename.as_deref()
146    }
147
148    /// Load source text from the file on disk for rich snippet rendering.
149    pub fn resolve_source(&mut self) {
150        if self.input.is_some() {
151            return;
152        }
153        if let Some(ref filename) = self.filename {
154            self.input = fs::read_to_string(filename).ok();
155        }
156    }
157}
158
159impl Display for Diagnostic {
160    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
161        let title = if self.message.is_empty() {
162            "unexpected token"
163        } else {
164            &self.message
165        };
166
167        let label = self.severity.label();
168        let Some(ref input) = self.input else {
169            // No source — render title only with filename
170            if let Some(ref filename) = self.filename {
171                return write!(f, "{label}: {title}\n --> {filename}");
172            }
173            return write!(f, "{label}: {title}");
174        };
175
176        let mut snippet = Snippet::source(input)
177            .fold(true)
178            .annotation(AnnotationKind::Primary.span(self.span.clone()));
179
180        if let Some(ref filename) = self.filename {
181            snippet = snippet.path(filename);
182        }
183
184        let group = self.severity.level().primary_title(title).element(snippet);
185
186        let renderer = Renderer::styled();
187        let output = renderer.render(&[group]);
188        write!(f, "{output}")
189    }
190}
191
192impl Error for Diagnostic {}
193
194/// A collection of compiler diagnostics.
195///
196/// Implements `Display` (joins all messages) and `Error`, so it can be
197/// converted to `anyhow::Error` with `?`.
198#[derive(Debug)]
199pub struct Diagnostics(pub Vec<Diagnostic>);
200
201impl Diagnostics {
202    /// Returns `true` if there are no diagnostics.
203    pub fn is_empty(&self) -> bool {
204        self.0.is_empty()
205    }
206
207    /// Resolve source text for all diagnostics (loads from disk).
208    pub fn resolve_sources(&mut self) {
209        for d in &mut self.0 {
210            d.resolve_source();
211        }
212    }
213
214    /// Turn a pass's accumulated errors into its result: `Ok(value)` if
215    /// `errors` is empty, else `Err` with sources resolved for rendering.
216    ///
217    /// Every pass follows the same shape — collect diagnostics into a
218    /// `Vec` as it walks the AST, then decide `Ok`/`Err` at the end — so
219    /// this replaces that boilerplate at each call site.
220    pub fn finish<T>(errors: Vec<Diagnostic>, value: T) -> Result<T, Self> {
221        if errors.is_empty() {
222            Ok(value)
223        } else {
224            let mut diags = Self(errors);
225            diags.resolve_sources();
226            Err(diags)
227        }
228    }
229
230    /// Every diagnostic as a warning, for a check whose findings are not
231    /// yet errors.
232    #[must_use]
233    pub fn as_warnings(self) -> Self {
234        Self(self.0.into_iter().map(Diagnostic::as_warning).collect())
235    }
236
237    /// Print a check's findings as warnings; the pass goes on.
238    pub fn warn(check: Result<(), Diagnostics>) {
239        if let Err(found) = check {
240            eprintln!("{}", found.as_warnings());
241        }
242    }
243
244    /// Take the warnings out of `diagnostics`, leaving the errors for
245    /// [`finish`](Self::finish).
246    pub fn warnings(diagnostics: &mut Vec<Diagnostic>) -> Self {
247        let (warnings, errors) = diagnostics
248            .drain(..)
249            .partition(|d| d.severity == Severity::Warning);
250        *diagnostics = errors;
251        let mut warnings = Self(warnings);
252        warnings.resolve_sources();
253        warnings
254    }
255}
256
257impl Display for Diagnostics {
258    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
259        for (i, d) in self.0.iter().enumerate() {
260            if i > 0 {
261                f.write_str("\n")?;
262            }
263            write!(f, "{d}")?;
264        }
265        Ok(())
266    }
267}
268
269impl Error for Diagnostics {}
270
271/// Format parse-stage errors with a filename attached to each.
272pub fn format_errors(errors: &[Diagnostic], filename: &str) -> String {
273    errors
274        .iter()
275        .map(|e| e.clone().with_filename(filename).to_string())
276        .collect::<Vec<_>>()
277        .join("\n")
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283
284    #[test]
285    fn a_warning_renders_with_its_own_label() {
286        let warning = Diagnostic::warn_at("x shadows y".to_owned(), 0..1, "p.fi");
287        assert_eq!(warning.severity(), Severity::Warning);
288        assert_eq!(warning.to_string(), "warning: x shadows y\n --> p.fi");
289
290        let error = Diagnostic::at("x shadows y".to_owned(), 0..1, "p.fi");
291        assert_eq!(error.severity(), Severity::Error);
292        assert_eq!(error.to_string(), "error: x shadows y\n --> p.fi");
293
294        let rendered = Diagnostic::new("odd".to_owned(), 0..1, "x: int;".to_owned());
295        assert!(rendered.to_string().contains("error"));
296        let rendered = Diagnostic {
297            severity: Severity::Warning,
298            ..rendered
299        };
300        assert!(rendered.to_string().contains("warning"));
301    }
302
303    #[test]
304    fn warnings_are_drained_and_errors_stay_in_order() {
305        fn texts(ds: &[Diagnostic]) -> Vec<&str> {
306            ds.iter().map(Diagnostic::message).collect()
307        }
308        let mut found = vec![
309            Diagnostic::warn_at("w1".to_owned(), 0..1, "p.fi"),
310            Diagnostic::at("e1".to_owned(), 1..2, "p.fi"),
311            Diagnostic::warn_at("w2".to_owned(), 2..3, "p.fi"),
312            Diagnostic::at("e2".to_owned(), 3..4, "p.fi"),
313        ];
314        let warnings = Diagnostics::warnings(&mut found);
315        assert_eq!(texts(&warnings.0), ["w1", "w2"]);
316        assert_eq!(texts(&found), ["e1", "e2"]);
317        assert!(Diagnostics::finish(found, ()).is_err());
318
319        let mut only = vec![Diagnostic::warn_at("w".to_owned(), 0..1, "p.fi")];
320        let warnings = Diagnostics::warnings(&mut only);
321        assert_eq!(warnings.0.len(), 1);
322        assert!(Diagnostics::finish(only, ()).is_ok());
323    }
324}